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

    1.先定义一些基础函数

     1 #include <iostream>
     2 
     3 using namespace std;
     4 
     5 void _swap(int& a, int& b)
     6 {
     7     int tmp = b;
     8     b = a;
     9     a = tmp;
    10 }
    11 
    12 int main()
    13 {
    14     int a[] = {1, 5, 3, 6, 9, 4, 2, 8, 7};
    15     int n = sizeof(a)/sizeof(a[0]);
    16     
    17     bubbleSort(a, n);  //具体算法见后面章节
    18     quickSort(a, n);
    19     insetSort(a, n);
    20     shellSort(a, n);
    21     selectSort(a, n);
    22     heapSort(a, n);
    23     mergeSort(a, n);
    24     
    25     for(int i = 0; i < n; i++)
    26     {
    27         cout << a[i] << "    ";
    28     }
    29     cout << endl;
    30     
    31     
    32     while(1);
    33     
    34     return 0;
    35 }

    2.冒泡排序

     1 void bubbleSort(int *arr, int n)
     2 {
     3     for(int i = 0; i < n; i++)
     4     {
     5         for(int j = 0; j< n - i - 1; j++)
     6         {
     7             if(arr[j] > arr[j+1])
     8             {
     9                 _swap(arr[j], arr[j+1]);
    10             }
    11         }
    12     }
    13 }

    3.快速排序

     1 int _part(int *arr, int start, int end)
     2 {
     3     int mid = start;
     4     while(start < end)
     5     {
     6         while(start < end && arr[end] >= arr[mid])  //此处 arr[end] >= arr[mid] 或是 arr[end] > arr[mid] 效果相同,无影响
     7         {
     8             --end;
     9         }
    10     
    11         while(start < end && arr[start] <= arr[mid]) //此处 arr[start] <= arr[mid] 或是 arr[start] < arr[mid] 效果相同,无影响
    12         {
    13             ++start;
    14         }
    15 
    16         if(start < end)
    17         {
    18             _swap(arr[start], arr[end]);
    19         }
    20     }
    21     
    22     _swap(arr[start], arr[mid]);
    23     
    24     return start;
    25 }
    26 
    27 void _quickSort(int *arr, int start, int end)
    28 {
    29     if(start >= end)
    30     {
    31         return;
    32     }
    33     
    34     int mid = _part(arr, start, end);
    35     _quickSort(arr, start, mid - 1);
    36     _quickSort(arr, mid + 1, end);
    37 }
    38 
    39 void quickSort(int *arr, int n)
    40 {
    41     _quickSort(arr, 0, n-1);
    42 }

      快速排序算法是使用最广泛的一种的算法,标准STL库中的sort算法就使用了快速排序算法,但是,不是单纯的使用了快速排序这一种算法,而是多种算法混合使用的一种算法,以快速排序算法为主,后续章节会在慢慢介绍。

  • 相关阅读:
    疑问
    linux 7.0+救援模式
    Unity3D手游开发日记(6)
    Unity3D手游开发日记(4)
    Unity3D手游开发日记(5)
    Unity3D手游开发日记(2)
    Unity3D手游开发日记(3)
    Unity3D手游开发日记(1)
    十大最佳Leap Motion体感控制器应用
    unity3d模型不接受光照
  • 原文地址:https://www.cnblogs.com/chusiyong/p/11319730.html
Copyright © 2011-2022 走看看