标签:快速排序
刚刚CVTE笔试,想写个快排,居然没写出来、写出来、出来、来!!!简直了,打死自己
再实现一遍吧!
#include <iostream> #include <stdio.h> void qsort(int first,int last,int* array,size_t size) { int left = first; int right = last; if (first >= last) return; int key = array[first]; int mid = first; while (first < last){ while (first < last && array[last] >= key) --last; if (first < last){ std::swap(array[first], array[last]); mid = last; } while (first < last&& array[first] <= key) ++first; if (first < last){ std::swap(array[first], array[last]); mid = first; } } qsort(left,mid-1,array,size); qsort(mid+1,right,array,size); } int main() { int array[7] = { 2, 3, -3, 1, 5, 4, 6 }; size_t size = sizeof(array) / sizeof(array[0]); qsort(0,size-1,array,size); system("pause"); return 0; }
顺便把归并也实现了一遍
#include <iostream> #include <stdio.h> void _mergearray(int* arr,int first,int mid, int last,int* p)//合并两个数组 { int i = first; int j = mid + 1; int m = mid; int n = last; int k = 0; while (i <= m && j <= n){ if (arr[i] <= arr[j]) p[k++] = arr[i++]; else p[k++] = arr[j++]; } while (i <= m) p[k++] = arr[i++]; while (j <= n) p[k++] = arr[j++]; for (int i = 0; i < k ; ++i) arr[first+i] = p[i]; } void _mergeSort(int* arr,int first,int last,int* p ) { int mid = first + ((last - first) >> 1); if (first < last){ _mergeSort(arr,first,mid,p);//使左边有序 _mergeSort(arr, mid+1, last, p);//使右边有序 _mergearray(arr,first,mid,last,p);//合并 } } void mergeSort(int* arr,int size) { int* p = new int[size];//p为辅助数组 if (p == NULL)return; _mergeSort(arr,0,size-1,p); delete[] p; } int main() { int array[7] = { 2, 3, -3, 1, 5, 4, 6 }; int size = sizeof(array) / sizeof(array[0]); //qsort(0,size-1,array,size); mergeSort(array, size); system("pause"); return 0; }
《完》
本文出自 “零蛋蛋” 博客,谢绝转载!
标签:快速排序
原文地址:http://lingdandan.blog.51cto.com/10697032/1835461