zoukankan      html  css  js  c++  java
  • 快排模板写法

    #include <iostream>
    using namespace std;
    
    //数组打印
    void P(int a[],int n)
    {
        for(int i=0; i<n; i++)
            cout<<a[i]<<" ";
        cout<<endl;
    }
    
    int quickSortPartition(int s[], int l, int r){
        //Swap(s[l], s[(l + r) / 2]); //若以中间数为基准,则先将中间的这个数和第一个数交换即可
        int i = l, j = r, x = s[l]; //将最左元素记录到x中
        while (i < j)
        {
            // 从右向左找第一个<x的数,无需考虑下标越界
            while(i < j && s[j] >= x)   j--;
            if(i < j)  s[i++] = s[j]; //直接替换掉最左元素(已在x中存有备份)
            
            // 从左向右找第一个>x的数
            while(i < j && s[i] <= x)   i++;
            if(i < j)   s[j--] = s[i];   //替换掉最右元素(已在最左元素中有备份),最左元素一定被覆盖过,若没有,则表明右侧所有元素都>x,那么算法将终止      
        }
        s[i] = x;  //i的位置放了x,所以其左侧都小于x,右侧y都大于x
        return i;
    }
    
    void quickSort(int s[], int l, int r)
    {
        //数组左界<右界才有意义,否则说明都已排好,直接返回即可
        if (l>=r)  return;
        
        // 划分,返回基准点位置
        int i = quickSortPartition(s, l, r);
        
        // 递归处理左右两部分,i处为分界点,不用管i了
        quickSort(s, l, i - 1);
        quickSort(s, i + 1, r);
    }
    
    int main()
    {
        int a[]= {72,6,57,88,60,42,83,73,48,85};
        //int a[]= {10,9,8,7,6,5,4,3,2,1};
        P(a,10);
        quickSort(a,0,9);//注意最后一个参数是n-1
        P(a,10);
        return 0;
    }
     s[j--] = s[i];

    //快速排序(从小到大)
    void quickSort(int left, int right, vector<int>& arr)
    {
        if(left >= right)
            return;
        int i, j, base, temp;
        i = left, j = right;
        base = arr[left];  //取最左边的数为基准数
        while (i < j)
        {
            while (arr[j] >= base && i < j)
                j--;
            while (arr[i] <= base && i < j)
                i++;
            if(i < j)
            {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
        //基准数归位
        arr[left] = arr[i];
        arr[i] = base;
        quickSort(left, i - 1, arr);//递归左边
        quickSort(i + 1, right, arr);//递归右边
    }
     
  • 相关阅读:
    Leetcode---2. Add Two Numbers
    Leetcode---1. Two Sum
    dpkg:处理 xxx (--configure)时出错解决方案
    ubuntu 14.04搭建tensorflow-gpu开发环境
    Leetcode---35. Search Insert Position
    Leetcode---21. Merge Two Sorted Lists
    Leetcode----26. Remove Duplicates from Sorted Array
    Leetcode---28. Implement strStr()
    Leetcode----27 Remove Element
    qemu 安装 ubuntu-server 虚拟机
  • 原文地址:https://www.cnblogs.com/stepping/p/15195934.html
Copyright © 2011-2022 走看看