快排中partition函数的优化

来源:互联网 发布:linux fdisk 编辑:程序博客网 时间:2024/06/10 00:43

       最近在看算法,发现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 elementint 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 elementint 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 sortif( 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 funtionint tmp = x;x = y;y = tmp;}void fastSort( int Arr[], int start, int end ){  //fast funtionint 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 --;}elsepst ++;}swap( Arr[ped], Arr[end] );   //swapfastSort( Arr,  pst, ped-1 );   //left sortfastSort( Arr,  ped+1, end );   //left sort}int main(){   //main funtionint Arr[]={2,7,4,3,6};fastSort( Arr, 0, 4);for(int i = 0; i<4; i++)cout<<i<<endl;return 0;}




0 0
原创粉丝点击