最近在看算法,发现patition函数可以有个比较简单的写法 ,因此写下来以后用得到:
// arr[]为数组,start、end分别为数组第一个元素和最后一个元素的索引
// povitIndex为选取的枢纽下标,关于枢纽下标的选取,wessi的书上有很好的讲解。
//本函数返回index值,在这个下标左边的数都比Arr[index]小,在这个下标右边的数都比Arr[index]大
int partition( int Arr[], int start, int end, int pivotIndex ) //pivotIndex 是枢纽元
{
int pivot = Arr[pivotIndex];
swap( Arr[pivotIndex], Arr[end]); //exchange the pivot and the last element
int indexStore = start;
for( int i = start; i < end; i++ )
{
if( Arr[i] < pivot )
{
swap( Arr[indexStore], Arr[i] );
indexStore ++;
}
}
swap( Arr[indexStore], Arr[end] );
return indexStore;
}
这个是快排程序,自己敲的,感觉挺简洁的。
/*****************************
@data:2015/7/1
@author:lss
@function:fast sort by using partition funtion
******************************/
#include <stdio.h>
#include <iostream>
using namespace std;
void swap( int &a, int &b ){ //交换函数
int tmp = a;
a = b;
b = tmp;
}
//本函数返回index值,在这个下标左边的数都比Arr[index]小,在这个下标右边的数都比Arr[index]大
int partition( int Arr[], int start, int end, int pivotIndex ) //pivotIndex 是枢纽元
{
int pivot = Arr[pivotIndex];
swap( Arr[pivotIndex], Arr[end]); //exchange the pivot and the last element
int indexStore = start;
for( int i = start; i < end; i++ )
{
if( Arr[i] < pivot )
{
swap( Arr[indexStore], Arr[i] );
indexStore ++;
}
}
swap( Arr[indexStore], Arr[end] );
return indexStore;
}
void fastSort( int Arr[], int start, int end ){ //快排主程序
if( start == end )
return;
int index = partition( Arr, start, end, start ); //得到index值,其实这个快排就是一个递归。
if( index > start )
fastSort(Arr, start, index-1 ); //left sort
if( index < end )
fastSort(Arr, index+1, end); //right sort
}
int main(){
int Arr[] = {3,2,4,7,4,56,1};
fastSort( Arr, 0, 6);
for(int i = 0 ; i <= 6; i++)
cout<<Arr[i]<<endl;
return 0;
}
这个是另外一中写法,很多书上可能都是这么写的。
/******************************
*@data:2015/6/16
*@author:lss
*@function:
test sort_fast
**********************************/
#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
void swap( int &x, int &y){ //swap funtion
int tmp = x;
x = y;
y = tmp;
}
void fastSort( int Arr[], int start, int end ){ //fast funtion
int pst = start;
int ped = end-1;
if( start == end && Arr == NULL)
return;
while( pst != ped ){
if( Arr[pst] >Arr[end] ){
swap( Arr[pst], Arr[ped]);
ped --;
}
else
pst ++;
}
swap( Arr[ped], Arr[end] ); //swap
fastSort( Arr, pst, ped-1 ); //left sort
fastSort( Arr, ped+1, end ); //left sort
}
int main(){ //main funtion
int
Arr[]={2,7,4,3,6};
fastSort( Arr, 0, 4);
for(int i = 0; i<4; i++)
cout<<i<<endl;
return 0;
}