zoukankan      html  css  js  c++  java
  • 快排算法C++模版

    此算法为复习数据结构笔记

    #include <iostream> 
    #include <ctime>
    using namespace std;
    
    //
    // 两值交换. 
    //
    template <typename T>
    void swap1(T &x, T &y)
    {
        T temp = x;
        x = y;
        y = temp;
    }
    
    //下标从0开始 
    template <typename T>
    int partition(T a[], int startIndex, int endIndex)
    {//快速排序中的一趟 
    	int i = startIndex;
    	int j = endIndex;
    	T key = a[startIndex];//作为枢轴来使用 
    	while (i < j)
    	{
    		while(i < j && a[j] >= key)
    			--j;
    		swap1(a[i], a[j]);
    		while(i < j && a[i] <= key)
    			++i;
    		swap1(a[j], a[i]);
    		
    	}
    	a[i] = key;
    	return i;
    
    }
    
    template <typename T>
    void qsort(T a[], int startIndex, int endIndex)
    {//快速排序的递归形式 
    	int loc;
    	if(startIndex < endIndex)
    	{
    		loc = partition(a, startIndex, endIndex);//一趟排序结果的调用 
    		qsort(a, startIndex, loc-1);
    		qsort(a, loc+1, endIndex);
    	}
    
    }
    
    int main() 
    { 
        srand(unsigned(time(NULL)));//set 种子  
    	int n =100;
        int a[100];  
        //产生随即数组  
        for(int i = 0; i < n; i++)  
        {  
    //       a[i] = rand()%100;  
    		a[i] = 100-i; 
        } 
        qsort(a, 0, n - 1); 
        for(int i = 0; i < n; i++) cout << a[i] << " "; 
        cout << endl; 
    
    	return 0;
    } 
    

      

  • 相关阅读:
    神经网络 初步
    SVM整理
    碎碎念
    random note
    2015阿里实习内推一轮被拒
    django开发框架-view & template
    一点思考
    dive into python 读笔(3)
    dive into python 读笔(2)
    dive into python 读笔(1)
  • 原文地址:https://www.cnblogs.com/daocaowu/p/3105695.html
Copyright © 2011-2022 走看看