标签:排序算法 while 快速排序 堆排序 val tar ons pbm jsb
1 public void insertSort(int[] arr){ 2 int n = arr.length; 3 for(int i =1;i<n;i++) 4 { 5 int value = arr[i]; 6 int j; 7 for(j= i; j>0 && value < arr[j-1];j--) 8 { 9 arr[j] = arr[j-1]; 10 } 11 arr[j] = value; 12 } 13 }
1 public void bubbleSort(int[] arr){ 2 int n = arr.length; 3 for (int i=0;i<n;i++){ 4 for (int j=0;j<n-i-1;j++){ 5 if(arr[j]>arr[j+1]){ 6 int t = arr[j+1]; 7 arr[j+1] = arr[j]; 8 arr[j] = t; 9 } 10 } 11 } 12 }
public void shellSort(int[] arr){ int n =arr.length; for (int gap = n/2;gap>0;gap = gap/2){ for (int i=gap;i<n;i++){ int j; int value = arr[i]; for (j=i-gap;j>=0&&arr[j]>value;j-=gap){ arr[j+gap] = arr[j]; } arr[j+gap] = value; } } }
public void selectSort(int[] arr){ int n = arr.length; for (int i=0;i<n-1;i++){ int position = i; for (int j=i+1;j<n;j++){ if(arr[j]<arr[position]){ position = j; } } int temp = arr[position]; arr[position] = arr[i]; arr[i] = temp; } }
1 public static void quickSort(int[] arr,int left,int right){ 2 //假设将right作为基准 3 if (left>right)return; 4 5 int index = left; 6 for (;left<right;left++){ 7 if (arr[left]<arr[right]){ 8 int temp = arr[left]; 9 arr[left] = arr[index]; 10 arr[index++] = temp; 11 } 12 } 13 14 if (index!=right){ 15 int temp = arr[right]; 16 arr[right] = arr[index]; 17 arr[index] = temp; 18 } 19 20 quickSort(arr,0,index-1); 21 quickSort(arr,index+1,right); 22 }
1 public void mergeSort(int[] arr,int start,int end){ 2 if (start>=end)return; 3 4 int mid =start+ (end-start)/2; 5 mergeSort(arr,start,mid); 6 mergeSort(arr,mid+1,end); 7 8 merge(arr,start,mid,end); 9 } 10 11 public static void merge(int[] arr,int start,int mid ,int end){ 12 int[] temp = new int[end-start+1]; 13 int i=0; 14 int p = start; 15 int q = mid+1; 16 while ( p <= mid && q<=end ){ 17 temp[i++] = arr[p]<=arr[q]?arr[p++]:arr[q++]; 18 } 19 20 if(p>mid){ 21 while (q<=end){ 22 temp[i++] = arr[q++]; 23 } 24 }else { 25 while (p<=mid){ 26 temp[i++] = arr[p++]; 27 } 28 } 29 30 for ( i =0;i<temp.length;i++){ 31 arr[start+i] = temp[i]; 32 } 33 34 }
1 public static void heapSort(int[] arr){ 2 int n = arr.length-1; 3 while (n>0){ 4 buildHeap(arr,n); 5 swap(arr,n,0); 6 n--; 7 } 8 } 9 10 public static void buildHeap(int[] a ,int n) 11 { 12 for(int i = (n-1)/2;i>=0;i--) //叶子节点没有子树,所以不需要比较 13 { 14 heapify(a,n,i); 15 } 16 } 17 18 public static void heapify(int[] a, int n,int i) 19 { 20 while(true) 21 { 22 int maxPosition = i; 23 if((i*2+1 <= n) && a[i] < a[i*2+1] ) maxPosition = i*2+1; 24 if((i*2+2 <= n ) && a[maxPosition] < a[i*2+2] ) maxPosition = i*2+2; 25 if(maxPosition == i ) break; 26 swap(a,i,maxPosition); 27 i = maxPosition; 28 } 29 } 30 31 public static void swap(int[] arr,int n,int i){ 32 int temp = arr[n]; 33 arr[n] = arr[i]; 34 arr[i] =temp; 35 }
标签:排序算法 while 快速排序 堆排序 val tar ons pbm jsb
原文地址:https://www.cnblogs.com/zwb1/p/12177857.html