1.冒泡排序
class BubbleSort {
public:
int* bubbleSort(int* A, int n) {
// write code here
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(A[j+1]<A[j])
swap(A[j],A[j+1]);
}
}
return A;
}
};
2.选择排序
class SelectionSort { public: int* selectionSort(int* A, int n) { // write code here for(int i=0;i<n;i++) { int temp=i; for(int j=i+1;j<n;j++) { if(A[j]<A[temp]) { temp=j; } } swap(A[temp],A[i]); } return A; } };
3.插入排序
4归并排序class InsertionSort { public: int* insertionSort(int* A, int n) { // write code here for(int i=1;i<n;i++) { if(A[i]<A[i-1]) { int temp=A[i]; int j=i; while(j>0&&A[j-1]>temp) { A[j]=A[j-1]; j--; } A[j]=temp; } } return A; } };
5.快速排序class MergeSort { public: int* mergeSort(int* A, int n) { // write code here merge(A,0,n-1); return A; } void merge(int *A,int l,int r) { if(l<r) { int mid=(l+r)/2; merge(A,l,mid); merge(A,mid+1,r); Sort(A,l,mid,r); } } void Sort(int *A,int l,int mid,int r) { int temp[r-l+1]; int x=l,y=mid+1; int t=0; while(x<=mid&&y<=r) { if(A[x]<A[y]) { temp[t++]=A[x]; x++; } else { temp[t++]=A[y]; y++; } } while(x<=mid) { temp[t++]=A[x]; x++; } while(y<=r) { temp[t++]=A[y]; y++; } for(int i=l;i<=r;i++) { A[i]=temp[i-l]; } } };
class QuickSort { public: int* quickSort(int* A, int n) { // write code here quicksort(A,0,n-1); return A; } void quicksort(int *A,int l,int r) { if(l<r) { int i=l,j=r,x=A[l]; while(i<j) { while(i<j&&A[j]>=x) j--; if(i<j) A[i++]=A[j]; while(i<j&&A[i]<x) i++; if(i<j) A[j--]=A[i]; } A[i]=x; quicksort(A,l,i-1); quicksort(A,i+1,r); } } };
6.堆排序class HeapSort { public: int* heapSort(int* A, int n) { // write code here for(int i=(n-1)/2;i>=0;i--) { Adjust(A,i,n); } for(int i=n-1;i>0;i--) { swap(A[i],A[0]); Adjust(A,0,i); } return A; } void Adjust(int* A,int x,int n) { int temp,child; for(temp=A[x];x*2+1<n;x=child) { child=x*2+1; if(child+1<n&&A[child+1]>A[child]) child++; if(temp<A[child]) A[x]=A[child]; else break; } A[x]=temp; } };
7.希尔排序class ShellSort { public: int* shellSort(int* A, int n) { // write code here int i,j,gap; for(gap=n/2;gap>0;gap/=2) { for(int i=gap;i<n;i++) { for(int j=i-gap;j>=0&&A[j]>A[j+gap];j-=gap) swap(A[j],A[j+gap]); } } return A; } };