C++中的几种排序算法

 更新时间:2020年4月25日 17:42  点击:1934

SortAlgorithm.h

复制代码 代码如下:

#include <vector>
using namespace std;

class SortAlgorithm
{
public:
    SortAlgorithm(int = 10);
    void displayVector();
    void swap(int &, int &);

    void insertSort();                     //O(n^2)
    void selectSort();                    //O(n^2)
    void mergeSort();                    //O(n log n)
    void bubbleSort();                  //O(n^2)
    void quickSort(  int , int  );     //worst: O(n^2),  best: O(n log n)

    int partition( int , int  );
    void sortSubVector(int , int );
    void merge(int , int , int , int );
private:
    int size;
    vector< int > source;
    vector< int > temp;

};

SortAlgorithm.cpp

复制代码 代码如下:

#include <iostream>
#include <cstdlib> // prototypes for functions srand and rand
#include <ctime> // prototype for function time
#include <algorithm> // prototype for sort function
#include "SortAlgorithm.h" // class BinarySearch definition
using namespace std;

SortAlgorithm::SortAlgorithm(int vectorSize)
{
    size = ( vectorSize > 0 ? vectorSize : 10 ); // validate vectorSize
    srand( time( 0 ) ); // seed using current time

   // fill vector with random ints in range 10-99
    for ( int i = 0; i < size; i++ )
           source.push_back( 10 + rand() % 90 ); // 10-99

    temp = source;
}

void SortAlgorithm::insertSort()
{
    int insert;
    for(int next = 1; next < size; next++){
        insert = temp[next];
        int moveItem = next;

        while((moveItem > 0) && (temp[moveItem - 1] > insert)){
            temp[moveItem] = temp[moveItem - 1];
            moveItem--;
        }

        temp[moveItem] = insert;
    }
}

void SortAlgorithm::selectSort()
{
    int loop = size - 1;
    int smallest;

    for(int i = 0; i < loop; i++){
        smallest = i;

        for(int j = i + 1; j < size; j++){
            if(temp[j] < temp[smallest])
                smallest = j;
        }

        swap(temp[i], temp[smallest]);
    }
}

void SortAlgorithm::mergeSort()
{
    sortSubVector(0, size - 1);
}

void SortAlgorithm::bubbleSort()
{
       int comp; // used to control for loop and for subscripts
       bool swapCheck = true; // was a swap made?

    for ( int pass = 1; pass < size && swapCheck; pass++ ) {
        swapCheck = false; // assume no swaps will be made

      // traverse and compare unsorted part of vector
        for ( comp = 0; comp < size - pass; comp++ ){

         // compare adjacent vector elements
            if ( temp[ comp ] > temp[ comp + 1 ] ) {
                swap(temp[comp], temp[comp + 1]);
                swapCheck = true;
                 } // end if

        } // end inner for
    } // end outer for
}

void SortAlgorithm::quickSort(int first, int last )
{
   int currentLocation;

   if ( first >= last )
      return;

   currentLocation = partition( first, last ); // place an element
   quickSort( first, currentLocation - 1 ); // sort left side
   quickSort( currentLocation + 1, last ); // sort right side
} // end function quickSortHelper

// partition the vector into multiple sections
int SortAlgorithm::partition( int left, int right )
{
   int position = left;

   // loop through the portion of the vector
   while ( true )
   {
   //first: from right ro left
      while ( temp[ position ] <= temp[ right ] && position != right )
         --right;

      if ( position == right )
         return position;

      if ( temp[ position ] > temp[ right ])
      {
         swap( temp[ position ], temp[ right ] );
         position = right;
      } // end if
   //second: from left to right
      while ( temp[ left ] <= temp[ position ] && left != position )
         ++left;

      if ( position == left )
         return position;

      if ( temp[ left ] > temp[ position ] )
      {
         swap( temp[ position ], temp[ left ] );
         position = left;
      } // end if
   } // end while
} // end function partition

void SortAlgorithm::sortSubVector(int low, int high)
{
    if((high - low) >= 1){
        int middle1 = (low + high) / 2;
        int middle2 = middle1 + 1;

        /*cout << "split:   ";
        displaySubVector(low, high);
        cout << endl << "       ";
        displaySubVector(low, middle1);
        cout << endl << "       ";
        displaySubVector(middle2, high);
        cout << endl << endl;*/

        sortSubVector(low, middle1);
        //cout << "Stop here1. low = " << low << ", middle1 = " << middle1 << endl;
        sortSubVector(middle2, high);
        //cout << "Stop here2. middle2 = " << middle2 << ", high = " << high << endl;

        merge(low, middle1, middle2, high);

    }
}

void SortAlgorithm::merge(int left, int middle1, int middle2, int right)
{
    int leftIndex = left;
    int rightIndex = middle2;
    int combinedIndex = left;
    vector<int> combined(size);

    /*cout << "merge:   ";
    displaySubVector(left, middle1);
    cout << endl << "       ";
    displaySubVector(middle2, right);
    cout << endl;*/

    while(leftIndex <= middle1 && rightIndex <= right){
        if(temp[leftIndex] <= temp[rightIndex])
            combined[combinedIndex++] = temp[leftIndex++];
        else
            combined[combinedIndex++] = temp[rightIndex++];
    }

    if(leftIndex == middle2){
        while(rightIndex <= right)
            combined[combinedIndex++] = temp[rightIndex++];
    }
    else{
        while(leftIndex <= middle1)
            combined[combinedIndex++] = temp[leftIndex++];
    }

    for(int i = left; i <= right; i++)
        temp[i] = combined[i];

    /*cout << "       ";
    displaySubVector(left, right);
    cout << endl << endl;*/
}

void SortAlgorithm::swap(int &x, int &y)
{
    int t;

    t = x;
    x = y;
    y = t;
}

void SortAlgorithm::displayVector()
{
    for(int i = 0; i < size; i++){
        cout << " " << temp[i];
        if((i + 1) % 10 == 0)
            cout << endl;
    }

    cout << endl;

    temp = source;
}

main.cpp

复制代码 代码如下:

#include <iostream>
#include "SortAlgorithm.h" // class BinarySearch definition
#include "BucketSort.h"
using namespace std;

int main()
{
    int num;
    cout << "Please input the integer number you want to sort:  ";
    cin >> num;

    SortAlgorithm sortVector(num);
    cout << "Unsort elements: \n";
    sortVector.displayVector();

    sortVector.insertSort();
    cout << "\nInsert sorted elements: \n";
    sortVector.displayVector();

    sortVector.selectSort();
    cout << "\nSelect sorted elements: \n";
    sortVector.displayVector();

    sortVector.mergeSort();
    cout << "\nMerge sorted elements: \n";
    sortVector.displayVector();

    sortVector.bubbleSort();
    cout << "\nBubble sorted elements: \n";
    sortVector.displayVector();

    sortVector.quickSort(0, num - 1);
    cout << "\nQuick sorted elements: \n";
    sortVector.displayVector();

   /*BucketSort bucketSortVector( num ); // create BucketSort object

   cout << "Vector elements in original order:\n";
   bucketSortVector.displayElements();

   bucketSortVector.sort(); // sort the vector

   cout << "\nVector elements in sorted order:\n";
   bucketSortVector.displayElements();*/
}

[!--infotagslink--]

相关文章

  • C++ STL标准库std::vector的使用详解

    vector是表示可以改变大小的数组的序列容器,本文主要介绍了C++STL标准库std::vector的使用详解,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2022-03-06
  • C++中取余运算的实现

    这篇文章主要介绍了C++中取余运算的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-23
  • C#几种排序算法

    作者:Sabine 【导读】本文介绍了C#的四种排序算法:冒泡排序、选择排序、插入排序和希尔排序  冒泡排序 using System; namespace BubbleSorter { public class Bubb...2020-06-25
  • 详解C++ string常用截取字符串方法

    这篇文章主要介绍了C++ string常用截取字符串方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-04-25
  • C++调用C#的DLL程序实现方法

    本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,下面就让我们一起来学习吧。...2020-06-25
  • C++中四种加密算法之AES源代码

    本篇文章主要介绍了C++中四种加密算法之AES源代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。...2020-04-25
  • C++ 整数拆分方法详解

    整数拆分,指把一个整数分解成若干个整数的和。本文重点给大家介绍C++ 整数拆分方法详解,非常不错,感兴趣的朋友一起学习吧...2020-04-25
  • C++中 Sort函数详细解析

    这篇文章主要介绍了C++中Sort函数详细解析,sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变...2022-08-18
  • C++万能库头文件在vs中的安装步骤(图文)

    这篇文章主要介绍了C++万能库头文件在vs中的安装步骤(图文),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-23
  • 详解C++ bitset用法

    这篇文章主要介绍了C++ bitset用法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-04-25
  • 浅谈C++中的string 类型占几个字节

    本篇文章小编并不是为大家讲解string类型的用法,而是讲解我个人比较好奇的问题,就是string 类型占几个字节...2020-04-25
  • C++ Eigen库计算矩阵特征值及特征向量

    这篇文章主要为大家详细介绍了C++ Eigen库计算矩阵特征值及特征向量,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-04-25
  • C++ pair的用法实例详解

    这篇文章主要介绍了C++ pair的用法实例详解的相关资料,需要的朋友可以参考下...2020-04-25
  • VSCode C++多文件编译的简单使用方法

    这篇文章主要介绍了VSCode C++多文件编译的简单使用方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-03-29
  • C++中的循环引用

    虽然C++11引入了智能指针的,但是开发人员在与内存的斗争问题上并没有解放,如果我门实用不当仍然有内存泄漏问题,其中智能指针的循环引用缺陷是最大的问题。下面通过实例代码给大家介绍c++中的循环引用,一起看看吧...2020-04-25
  • C++随机点名生成器实例代码(老师们的福音!)

    这篇文章主要给大家介绍了关于C++随机点名生成器的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-04-25
  • 图文详解Heap Sort堆排序算法及JavaScript的代码实现

    这篇文章以图文详解Heap Sort堆排序算法及JavaScript的代码实现,堆排序算法基于类二叉树的堆数据结构,需要的朋友可以参考下...2016-05-05
  • C++如何删除map容器中指定值的元素详解

    map容器是C++ STL中的重要一员,删除map容器中value为指定元素的问题是我们经常与遇到的一个问题,下面这篇文章主要给大家介绍了关于利用C++如何删除map容器中指定值的元素的相关资料,需要的朋友可以参考借鉴,下面来一起看看吧。...2020-04-25
  • C++ 约瑟夫环问题案例详解

    这篇文章主要介绍了C++ 约瑟夫环问题案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下...2021-08-15
  • C++中cin的用法详细

    这篇文章主要介绍了C++中cin的用法详细,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-04-25