数据结构常考的排序
#include<iostream>
using namespace std;
void show(int arr[],int n) {
for(int i=0; i<n; i++) {
cout<<arr[i]<<" ";
}
cout<<endl;
}
void quickSort(int arr[],int left,int right) {
if(left>=right)return;
int p=arr[left];
int pos=left;
for(int i=left+1; i<=right; i++) {
if(arr[i]<p) {
pos++;
if(pos!=i) {
int temp=arr[pos];
arr[pos]=arr[i];
arr[i]=temp;
}
}
}
arr[left]=arr[pos];
arr[pos]=p;
quickSort(arr,left,pos-1);
quickSort(arr,pos+1,right);
}
void quickSort(int arr[],int n) {
quickSort(arr,0,n-1);
cout<<"The result of quickSort is:";
show(arr,n);
}
void insertSort(int arr[],int left,int right) {
for(int i=left+1; i<=right; i++) {
if(arr[i-1]>arr[i]) {
int temp=arr[i];
int j=i-1;
do {
arr[j+1]=arr[j];
j--;
} while(j>=left&&arr[j]>temp);
arr[j+1]=temp;
}
}
}
void insertSort(int arr[],int n) {
insertSort(arr,0,n-1);
cout<<"The result of insertSort is:";
show(arr,n);
}
void binaryInsertSort(int arr[],int left,int right) {
for(int i=left+1; i<=right; i++) {
if(arr[i-1]>arr[i]) {
int temp=arr[i];
int low=left,high=i-1;
while(low<=high) {
int mid=(low+high)/2;
if(temp<arr[mid]) {
high=mid-1;
} else {
low=mid+1;
}
}
for(int k=i-1; k>=low; k--) arr[k+1]=arr[k];
arr[low]=temp;
}
}
}
void binaryInsertSort(int arr[],int n) {
binaryInsertSort(arr,0,n-1);
cout<<"The result of binaryInsertSort is:";
show(arr,n);
}
void shellSort(int arr[],int left,int right){
int gap=right-left+1;
do{
gap=gap/3+1;
for(int i=left+gap;i<=right;i++){
if(arr[i-gap]>arr[i]){
int temp=arr[i];
int j=i-gap;
do{
arr[j+1]=arr[j];
j-=gap;
}while(j>=left&&arr[i-gap]>temp);
arr[j+1]=temp;
}
}
} while(gap>1);
}
void shellSort(int arr[],int n) {
shellSort(arr,0,n-1);
cout<<"The result of shellSort is:";
show(arr,n);
}
void merge(int arr[],int left,int mid,int right){
int* brr=new int[right-left+1];
for(int i=left;i<=right;i++){
brr[i]=arr[i];
}
int s1=left,s2=mid+1,t=left;
while(s1<=mid&&s2<=right){
brr[s1]<=brr[s2]?arr[t++]=brr[s1++]:arr[t++]=brr[s2++];
}
while(s1<=mid)arr[t++]=brr[s1++];
while(s2<=right)arr[t++]=brr[s2++];
delete[] brr;
return;
}
void mergeSort(int arr[],int left,int right){
if(left>=right)return;
int mid=(left+right)/2;
mergeSort(arr,left,mid);
mergeSort(arr,mid+1,right);
merge(arr,left,mid,right);
}
void mergeSort(int arr[],int n) {
mergeSort(arr,0,n-1);
cout<<"The result of mergeSort is:";
show(arr,n);
}
int main() {
int n;
cin>>n;
int* arr=new int[n];
for(int i=0; i<n; i++) {
cin>>arr[i];
}
quickSort(arr,n);
insertSort(arr,n);
binaryInsertSort(arr,n);
shellSort(arr,n);
mergeSort(arr,n);
return 0;
}