zoukankan      html  css  js  c++  java
  • C++ 实现简单快速排序

    #include<iostream>
    #include <unistd.h>
    using namespace std;
    
    #define LOG(s)
    cout<<s<<endl;
    
    void printArray(int a[],int len)
    {
    	for(int i=0;i<len;i++){
    		cout<<a[i]<<'	';
    	}
    	cout<<endl;
    }
    
    void exchange(int a[],int f,int s){
    	int tmp = a[f];
    	a[f] = a[s];
    	a[s] = tmp;
    }
    
    void quicksort(int a[],int low,int high)
    {
    	if (low > high) return;
    	int i,j,tmp,t;
    	i = low;
    	j = high;
    	tmp = a[low];
    	while(i < j){
    		while(tmp <= a[j] && i < j){
    			j--;
    		}
    		while(tmp >= a[i] && i < j){
    			i++;
    		}
    		if(i<j){
    			exchange(a,i,j);
    		}
    	}
    	exchange(a,low,i);
    	printArray(a,6);
    	// sleep(5.0);
    	quicksort(a,low,j-1);
    	quicksort(a,j+1,high);
    }
    
    int main()
    {
    	int a[] = {7,4,9,2,12,8};	
    	quicksort(a,0,5);
    	return 0;
    }
    

    快速排序可以简单的理解为二分,每次把最前面的一个数送到合适的位置,这样再递归的处理这个数分割后的两个数组,这样,假设有n个数,那么就需要把n个数送到合适的位置,就会递归的调用N次,哪怕后面的调用中已经不发生位置的交换。

  • 相关阅读:
    this指针详解
    C++处理异常
    C++中的this指针
    c++中的string类
    c面试题总结
    c++中的引用详解
    c++中的new和delete
    函数重载
    BST(二叉排序树)的插入与删除
    ccf行车路线
  • 原文地址:https://www.cnblogs.com/walnuttree/p/10762724.html
Copyright © 2011-2022 走看看