快速排序:
每次排序一个元素,每次使他的左边都比他小,右边都比他大;
和归并排序相似;
递归函数:
void Quick_sort(int *arr,int low,int hight)
{if(low < hight){int x = Quick(arr,low,hight);Quick_sort(arr,low,x-1);Quick_sort(arr,x+1,hight);}
}
先排序low位置的元素
然后返回他排序后的位置
接着排序他左边和右边
递归直到只剩一个元素
排序函数;
int Quick(int *arr,int low,int hight)
{int t;t = arr[low];while(low < hight){while(low < hight && arr[hight] >= t){--hight;}arr[low] = arr[hight];while(low < hight && arr[low] <= t){++low;}arr[hight] = arr[low];}arr[low] = t;return low;
}
先用一个变量t存储元素,从左右两端循环,因为排序的元素是最左端元素,所以应该先从右侧开始,如果遇到了小于t的元素,就将左侧覆盖为他,接着从左端开始,如果遇到比t大的元素就将他覆盖到右边,直到low == hight;这个时候的位置就是左侧数都小于t,右侧数都大于t,将t插入后返回即可
c++代码如下:
#include <bits/stdc++.h>using namespace std;void swap(int &a,int &b)
{int t = a;a = b;b = t;
}int Quick(int *arr,int low,int hight)
{int t;t = arr[low];while(low < hight){while(low < hight && arr[hight] >= t){--hight;}arr[low] = arr[hight];while(low < hight && arr[low] <= t){++low;}arr[hight] = arr[low];}arr[low] = t;return low;
}void Quick_sort(int *arr,int low,int hight)
{if(low < hight){int x = Quick(arr,low,hight);Quick_sort(arr,low,x-1);Quick_sort(arr,x+1,hight);}
}void print_arr(int *arr,int size)
{for(int i = 0;i < size;++i){cout << arr[i];if(i != size-1){cout << " ";}}
}int main()
{int n;cin >> n;int arr[n];for(int i = 0;i < n;++i){cin >> arr[i];}Selection_sort(arr,n);print_arr(arr,n);cout << endl;
}