#include
#include
using namespace std;
//int arr[11]= {3423,4,6,2,8,3,1,34,234,523,1234};
void printArray(int arr[], int num){
for(int i=0;i
cout<
void swap(int& a,int&b){
int temp = a;
a = b;
b = temp;
}
void initArray(int arr[], int n){
srand(time(0));
for(int i=0;i
}
}
void bubbleSort(int arr[],int n){
for(int i=0; i
swap(arr[j],arr[j+1]);
}
}
}
}
void cocktailSort(int arr[], int n){
bool swaped = true;
int start=0, end = n-1;
while(swaped){
swaped = false;
for(int i=start; i
swap(arr[i],arr[i+1]);
swaped = true;
}
}
end--;
for(int i=end; i>start; i--){
if(arr[i] < arr[i-1]){
swap(arr[i],arr[i-1]);
swaped = true;
}
}
start++;
}
}
void originInsertSort(int arr[], int n){
for(int i=1;i
int j = i-1;
while(temp
arr[j+1] = arr[j];
j--;
}
arr[j+1] = temp;
}
}
void recurInsertSort(int arr[],int n){
if(n==1) return;
recurInsertSort(arr,n-1);
int temp = arr[n-1];
int i=n-2;
while(arr[i]>temp && i>=0){
arr[i+1] = arr[i];
i--;
}
arr[i+1] = temp;
}
void binaryInsertSort(int arr[],int n){
for(int i=1;i
while(low<=high){
int middle = (low+high)/2;
if(temp
}else{
low = middle+1;
}
}
//copy from low to i
for(int j=i-1;j>=low;j--){
arr[j+1] = arr[j];
}
arr[low] = temp;
}
}
void filterDown(int arr[], int heapSize, int start){
int left = (start<<1)+1;
int right = (start<<1)+2;
int largest = start;
if(left
largest = left;
}if(right
largest = right;
}
if(largest!= start){
swap(arr[start],arr[largest]);
filterDown(arr,heapSize,largest);
}
}
void buildSort(int arr[], int n){
for(int i=n/2-1; i>=0;i--){
filterDown(arr,n,i);
}
}
void heapSort(int arr[], int n){
buildSort(arr,n);
//printArray(arr,n);
int size = n;
for(int i=n-1; i>0; i--){
swap(arr[i],arr[0]);
filterDown(arr,--size,0);
}
}
int partiton(int arr[], int p, int r){
int i=p-1;
int splite = arr[r];
for(int j=p; j
swap(arr[++i],arr[j]);
}
}
swap(arr[++i], arr[r]);
return i;
}
void quickSort(int arr[], int p, int r){
if(p
quickSort(arr,p,q-1);
quickSort(arr,q+1,r);
}
}
void merge(int arr[], int p,int r){
int i=p;
int middle = (p+r)/2;
int j = middle+1;
int* ap = (int*)malloc((r-p+1)*sizeof(int));
memcpy(ap,&arr[p],(r-p+1)*sizeof(int));
int counter = p;
while(i<= middle && j<=r){
if(ap[i-p] < ap[j-p]){
arr[counter++] = ap[i-p];
i++;
}else{
arr[counter++] = ap[j-p];
j++;
}
}
while(i<=middle){
arr[counter++] = ap[i-p];
i++;
}
while(j<=r){
arr[counter++] = ap[j-p];
j++;
}
free(ap);
}
void mergeSort(int arr[], int p, int r){
if(p
mergeSort(arr,p,middle);
mergeSort(arr,middle+1,r);
merge(arr,p,r);
}
}
void main(){
const int ARRD = 20;
int arr[ARRD];
initArray(arr,ARRD);
cout<<"before sort"<
cout<<"after sort" <
//cocktailSort(arr,ARRD);
//originInsertSort(arr,ARRD);
//binaryInsertSort(arr,ARRD);
// recurInsertSort(arr,ARRD);
//heapSort(arr,ARRD);
quickSort(arr,0,ARRD-1);
printArray(arr,ARRD);
}
欢迎批评指正,共同进步