zoukankan      html  css  js  c++  java
  • 交换排序

    冒泡排序

    基本思想:在要排序的一组数中,对当前还未排好序的范围内的全部数,自上而下对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的往上冒。

    void bubbleSort(int a[],int n)
    {
        for(int i=0;i<n-1;i++)
            for(int j=0;j<n-1-i;j++)
        {
            if(a[j]>a[j+1])
            {
                int tmp=a[j];
                a[j]=a[j+1];
                a[j+1]=tmp;
            }
        }
    }

    快速排序的基本思想:

    (1)选择一个基准元素,通常选第一个或者最后一个元素。

    (2)通过一趟排序之后将待排序的记录分割成独立的两部分,其中一部分的记录的元素值均比基准元素值小,另一部分记录的元素均比基准元素值大。

    (3)此时基准元素在其排好序的正确位置

    (4)然后分别对这两部分的记录用同样的方法继续进行排序,直到整个序列有序,快排完毕。

    具体代码如下:

     1 //快速排序
     2 
     3 void print(int a[],int n)
     4 {
     5     for(int j=0;j<n;j++)
     6         cout<<a[j]<<" ";
     7 
     8     cout<<endl;
     9 }
    10 
    11 void swap_int(int *a,int *b)
    12 {
    13     int tmp=*a;
    14     *a=*b;
    15     *b=tmp;
    16 }
    17 
    18 int sort_partition(int a[],int low,int high)
    19 {
    20     int privotkey=a[low];
    21     while(low<high)
    22     {
    23         while(low<high && a[high]>=privotkey) --high;
    24         swap_int(&a[low],&a[high]);
    25         while(low<high && a[low]<=privotkey) ++low;
    26         swap_int(&a[low],&a[high]);
    27     }
    28     print(a,10);
    29     return low;
    30 }
    31 
    32 //采用递归的方式快速排序
    33 void quickSort(int a[],int low,int high)
    34 {
    35     if(low<high)
    36     {
    37         int privotLoc=sort_partition(a,low,high);  //将表一分为二
    38         quickSort(a,low,privotLoc-1);
    39         quickSort(a,privotLoc+1,high);
    40     }
    41 }
    42 
    43 int main()
    44 {
    45     int a[10]={3,1,5,7,2,4,9,6,10,8};
    46     quickSort(a,0,9);
    47     print(a,10);
    48 }
  • 相关阅读:
    浙江理工2015.12校赛-F Landlocked
    浙江理工2015.12校赛-G Jug Hard
    浙江理工2015.12校赛-B 七龙珠
    浙江理工2015.12校赛-A
    Smallest Bounding Rectangle
    Just a Hook(HDU1698 线段树的简单应用)
    覆盖的面积(HDU 1255 线段树)
    Prime Query (ZOJ 3911 线段树)
    JuQueen(线段树 lazy)
    2015弱校联盟(2)
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/5146440.html
Copyright © 2011-2022 走看看