快速排序的C++與R語言實現


快速排序基本思想通過一趟排序將要排序的數據分割成獨立的兩部分,其中一部分的所有數據都比不小於另外一部分的所有數據,然後再按此方法對這兩部分數據分別進行快速排序,整個排序過程可以遞歸進行,以此達到整個數據變成有序序列。


1.C++實現

    C++實現的代碼:

#include 
#include 
using namespace std;
int calcute(int a[], int low, int high)
{
	int pivortkey = a[low]; //用數組的第一個值作爲比較的樞紐值
	while (low < high) //直到low = high終止
	{
		while (pivortkey <= a[high] && low < high)
		{
			high--;  //從數組的尾部向頭部遍歷數組數據
		}
		a[low] = a[high];  //將比pivortkey小的數放在前面		
		while (pivortkey >= a[low] && low < high)
		{
			low++;  //從數組的頭部向尾部遍歷數組數據
		}				
		a[high] = a[low]; //將比pivortkey大的數放在後面		
	}
	a[low] = pivortkey; //將pivortkey放在low=high的位置(前小後大)
	return low;  //返回樞紐值所在的位置
}
void quicksort(int a[], int low, int high)
{
	int index;		
	if (low >= high)
	{
		return;  //單個分支調用結束時返回,遞歸的結束標誌
	}
	if (low < high)
	{
		index = calcute(a, low, high);   //將源數組以樞紐a[low]爲界分兩個分支
		quicksort(a, low, index - 1);    //遞歸調用,以樞紐爲界:小於或等於樞紐值a[low]的分支
		quicksort(a, index + 1, high);   //遞歸調用,以樞紐爲界:大於或等於樞紐值a[low]的分支
	}	
}
int main(int argc, char* argv[])
{
	int a[10];
	cout << "Please input 10 numbers:\n";
	for (int i = 0; i < 10; i++)
	{
		cout << "The " << i << "th: ";
		cin >> a[i];    //獲取輸入值,每輸入一個值按enter結束
	}		
	quicksort(a, 0, 9);  
	cout << "After quicksort:";
	for (int i = 0; i<10; i++)
	{
		cout << a[i] << " "; //輸出結果,以空格分隔
	}
	cout << endl;	 
	return 0;
}

    C++實現的輸出結果:

  

 

2.R語言實現

    R語言實現的代碼:

quicksort <- function(x)
{  
    if (length(x) <= 1)
    { 
        return(x)   #終止條件  
    }
    pivot <- x[1]      #設定樞紐值  
    therest <- x[-1]   #選取除去樞紐值的其餘部分值  
    sv1 <- therest[therest < pivot]   #小於樞紐值的部分值  
    sv2 <- therest[therest >= pivot] #不小於樞紐值的部分值  
    sv1 <- quicksort(sv1)      #對分支sv1進行遞歸調用  
    sv2 <- quicksort(sv2)      #對分支sv2進行遞歸調用  
    return (c(sv1, pivot, sv2))  #返回排序後的結果向量    
}

    R語言實現的輸出結果:

   


總結:快速排序算法是排序算法中的基本算法之一,本文分別通過編譯型語言C++和解釋型語言R實現這種算法。兩種語言都達到了目標,但從代碼的簡潔性上看,R語言略勝一籌。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章