#include<iostream>
using namespace std;
/*
经典的双向快速排序
*/
int partition1(int array[], int start, int end){
if(array == NULL || start>end)
return -1;
int pivot=array[start];
while(start<end){
while(start<end && array[end]>=pivot)
end--;
if(start<end)
array[start]=array[end];
while(start<end && array[start]<pivot)
start++;
if(start<end)
array[end]=array[start];
}
array[start]=pivot;
return start;
}
/*
单方向的快速排序
*/
int partition2(int array[], int start, int end){
if(array == NULL || start >= end)
return -1;
int pivot=array[end];
int slow=start-1;
int fast=start;
while(fast<end){
if(array[fast]>=pivot)
fast++;
else{
swap(array[++slow], array[fast]);
fast++; //这步不能少,如 5 6
}
}
swap(array[++slow], array[end]);
return slow;
}
void QuickSort(int array[], int len){
if(array==NULL || len<=0)
return;
int index=partition2(array, 0, len-1);
partition2(array, 0, index-1);
partition2(array, index+1, len-1);
}
/*
* 复杂度,最坏情况下:Θ(n^2)
* 一般平衡情况:Θ(nlgn)
* @param array 待排数组
* @param from 起始位置
* @param to 终止位置
*/
void quickSort(int array[], int from, int to) {
if (from < to) {
int temp = array[to];
int i = from - 1;
for (int j = from; j < to; j++) {
if (array[j] <= temp) {
i++;
int tempValue = array[j];
array[j] = array[i];
array[i] = tempValue;
}
}
array[to] = array[i+1];
array[i+1] = temp;
quickSort(array, from, i);
quickSort(array, i + 1, to);
}
}
/*
二分查找算法
*/
int BinarySearch(int array[], int len, int val){
if(array == NULL || len<=0 )
return -1;
int low=0, high=len-1;
int mid=len>>1;
while(low<=high){
if(array[mid] == val)
return mid;
else if(array[mid] > val)
high=mid-1;
else low=mid+1;
mid=low+(high-low)>>1;
}
return -1;
}
/*
找出数组中最小的K个数
*/
void FindMinKNumber(int array[], int len, int k){
if(array == NULL || len <= 0 || k>len)
return;
int index=partition1(array, 0, len-1);
//int low=0, high=len-1;
while(index != k){
if(index > k)
index=partition1(array, 0, index-1);
else index=partition1(array, index+1, len-1);
cout<<index<<endl;
}
for(int i=0; i<k; i++)
cout<<array[i]<<' ';
}
int main(){
int array[]={5, 4, 3, 6, 2, 5};
FindMinKNumber(array,sizeof(array)/sizeof(int), 3);
QuickSort(array, sizeof(array)/sizeof(int));
for(int i=0; i<sizeof(array)/sizeof(int); i++)
cout<<array[i];
cout<<endl;
int index=BinarySearch(array, sizeof(array)/sizeof(int), 3);
if(index == -1)
cout<<"not find"<<endl;
else cout<<"found in "<<index<<endl;
system("pause");
}