HankerRank刷题第四天(排序类型)Quicksort In-Place
真是不能坚持啊.
坚持一下嘛
题目地址:https://www.hackerrank.com/challenges/quicksort3
快速排序算法的一种变形:
把算法步骤都描述了,只是需要实现出来
选取数组最后一个元素作为key,如果比key大则不变,比key小则将其与目前发现的第一个比key大的元素进行交换
代码:
#include <iostream> #include <vector> #include <cstdio> using namespace std; int v[5005]; int n; void print() { for(int i=0;i<n;i++) { printf("%d ",v[i]); } printf("\n"); } void change(int i,int j) { int temp; temp=v[i]; v[i]=v[j]; v[j]=temp; } void quicksort(int left, int right){ if(left<right) { int low=left; int high=left; int key=v[right]; while(high<=right) { while(v[high]>key) { high++; } change(high,low); high++; low++; } print(); quicksort(left,low-2); quicksort(low,right); } } int main() { //freopen("a.txt","rw",stdin); scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&v[i]); } quicksort(0,n-1); return 0; }
顺便再附上快速排序的代码:
void quickSort(int left,int right){ if(left<right){ int key=v[left]; int low=left; int high=right; while(low<high){ while(low<high&&v[high]>key){ high--; } v[low]=v[high]; while(low<high&&v[low]<key){ low++; } v[high]=v[low]; } print(); //输出每一步 v[low]=key; quickSort(left,low-1); quickSort(low+1,right); } }