学习排序,写了快速排序和堆排序的函数。
Sort.java - package sort;
- import java.lang.*;
- /**
- *
- * @author Firwood
- */
- public class Sort {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- // TODO code application logic here
- System.out.println("This is Test");
- Quicks h = new Quicks(10);
- for(int i=0;i<h.length;i++) {
- h.a[i] = (int)(Math.random()*100);
- }
- h.Output();
- System.out.println("------------------------------------------------------");
- //h.Build();
- h.sort();
- h.Output();
- }
- }
复制代码Quicks.java - package sort;
- public class Quicks {
- //
- int[] a;
- int length;
- Quicks() {//默认生成20个元素的数组来存储数字
- a = new int[20];
- length = 20;
- }
- Quicks(int x) {
- a = new int[x];
- length = x;
- }
- int Part(int p, int r) {
- int x = a[r];
- int i = p - 1;
- for( int j = p; j <= r-1; j++) {
- if( a[j] <= x ) {
- i++;
- int temp = a[i];
- a[i] = a[j];
- a[j] = temp;
- }
- }
- int tem = a[i+1];
- a[i+1] = a[r];
- a[r] = tem;
- return i+1;
- }
- int Quicksort(int p, int r) {
- if( p < r ) {
- int q = Part(p,r);
- Quicksort(p,q-1);//排序前一部分
- Quicksort(q+1,r);//排序后一部分
- }
- return 0;
- }
- int sort() {
- Quicksort(0,length-1);
- return 0;
- }
- int Output() {//输出数组的内容
- for(int i=0;i<length;i++) {
- System.out.printf("%d ",a[i]);
- }
- System.out.printf("\n");
- return 0;
- }
- }
复制代码Heapt.java - package sort;
- import java.lang.*;
- public class Heapt {
- int[] a;
- int length;
- Heapt() {
- a = new int[20];
- length = 20;
- }
- Heapt(int n) {
- a = new int[n];
- length = n;
- }
-
- int left(int i) {
- return 2*i+1;
- }
- int right(int i) {
- return 2*i+2;
- }
- int parent(int i) {
- return ((i+1)/2-1);
- }
- int exchange(int x,int y) {
- int temp = a[x];
- a[x] = a[y];
- a[y] = temp;
- return 0;
- }
- int Max_Heap(int i,int len) {
- int r = right(i);
- int l = left(i);
- int p = parent(i);
-
- int largest = i;
- if(l < len && a[l] > a[largest]) largest = l;
- else largest = i;
-
- if(r < len && a[r] > a[largest]) largest = r;
-
- if(largest != i) {
- exchange(i,largest);
- Max_Heap(largest,len);
- }
-
- return 0;
- }
- int Build() {
- for(int i=(length)/2; i>=0;i--) {
- Max_Heap(i,length);
- }
- return 0;
- }
- int sort() {
- Build();
- int tt = length;
- while(tt > 1) {
- tt--;
- exchange(0,tt);
- Max_Heap(0,tt);
- }
- return 0;
- }
- int Output() {
- for(int i=0;i<length;i++) {
- System.out.printf("%d ",a[i]);
- }
- System.out.printf("\n");
- return 0;
- }
-
- }
复制代码
|
|