简单选择排序
#include <iostream> using namespace std; void swap(int &a,int &b) { int temp = a; a=b ; b=temp; } void choiceSort(int A[],int n) { for(int i=0;i<n-1;++i) { int min_index= i; for(int j=i;j<n;++j) { if(A[j]<A[min_index]) min_index=j; } swap(A[i],A[min_index]); } } int main(int argc, char *argv[]) { int A[10]={ 99,0,2,15,88,34,10,4,56,11 }; choiceSort(A,10); for(int i=0;i<10;++i) { cout<<A[i]<<" "; } cout<<endl; return 0; }
冒泡排序
插入排序
双向冒泡
package com.google.app; public class Animal { public static void bubble_sort(int[] A){ for(int i=0;i<A.length-1;i++){ for(int j=0;j<A.length-i-1 ; ++j){ if(A[j]>A[j+1]){ int temp = A[j]; A[j]=A[j+1]; A[j+1]=temp; } } } } public static void dbubble_sort(int[] A){ for(int i=0;i<A.length-1;i++){ for(int j=0;j<A.length-i-1; ++j){ if(A[j]>A[j+1]){ int temp = A[j]; A[j]=A[j+1]; A[j+1]=temp; } if(A[A.length-i-j-1]<A[A.length-i-j-2]){ int temp = A[A.length-i-j-1]; A[A.length-i-j-1] = A[A.length-i-j-2]; A[A.length-i-j-2] = temp; } } } } public static void insert_sort(int[] A){ int j; int temp; for(int i=1;i<A.length;++i){ j=i-1; temp=A[i]; while(j>=0 && A[j]>temp ){ A[j+1]=A[j]; j--; } A[j+1]=temp; } } public static void main(String[] args) { int[] A={99,88,77,66,55,44,33,22,11}; dbubble_sort(A); //insert_sort(A); for (int i : A) { System.out.print(i+" "); } } }快速排序
int partion(int A[],int left,int right) { int pivot = A[left]; while(left<right) { while(left < right && A[right]>=pivot) right--; A[left]=A[right]; while(left < right && A[left]<=pivot) left++; A[right]=A[left]; } A[left] = pivot; return left; } void quickSort(int A[],int left,int right) { if(left < right) { int pos = partion(A,left,right); quickSort(A,left,pos-1); quickSort(A,pos+1,right); } }
希尔排序
#include <iostream> using namespace std; void ShellSort(int A[],int n) { for(int dk = n/2;dk>=1;dk = dk/2) { for(int k=0;k<dk;k++) { for(int i=k+dk;i<n;i++) { int temp= A[i]; int j=i-dk; while(j>=0 && A[j]>temp) { A[j+dk] = A[j]; j=j-dk; } A[j+dk] = temp; } } } } int main(int argc, char *argv[]) { int A[10]={ 99,0,2,15,88,34,10,4,56,11 }; ShellSort(A,10); for(int i=0;i<10;++i) { cout<<A[i]<<" "; } cout<<endl; }
折半插入
void BiInsertSort(int A[],int n) { int low,high,mid; int temp; for(int i=1;i<n;i++) { low = 0; high = i-1; temp=A[i]; while(low<=high) { mid=(low+high)/2; if(A[mid] == temp) { high=mid-1; break; } else if(A[mid] < temp) { low = mid+1; }else{ high = mid-1; } } for(int j=i-1;j>=high+1;j--) { A[j+1]=A[j]; } A[high+1]=temp; } } void InsertSort(int A[],int n) { for(int i=1;i<n;++i) { int j = i-1; int temp = A[i]; while(j>=0 && A[j]>temp) { A[j+1] = A[j]; j--; } A[j+1]=temp; } }