经典算法与数据结构的c++实现——冒泡排序

来源:互联网 发布:dz论坛seo 编辑:程序博客网 时间:2024/05/16 15:41

因为是经典的算法,所以网上描述一大把,直接上个图,直观些,给记性不好的(如我)一点儿提示。


下面是代码(欢迎批评指点,之后应该会放到github上:https://github.com/y277an/princeton_algs4):

//---------------------------------Specification of Program------------------------------// Program Name:冒泡排序// Tools:VS_2013// Language: C++// Description: 可自由输入,不需要提早知道数据长度// Date:2016.3.14// Author:mseddl//----------------------------------------------------------------------------------------#include<iostream>using namespace std;void BubbleSort(int* arr,int count){for (int i = 0; i < count; i++){for (int j = 0; j < (count - i-1); j++){if (arr[j]>arr[j + 1]){int temp = arr[j];arr[j] = arr[j + 1];arr[j + 1] = temp;}}}}void main(){int* arr = new int[1000];int count(0), temp;char ch;cout << "输入数字,以空格隔开:";while (1){cin >> temp;cin.get(ch);arr[count++] = temp;if (ch == '\n')break;}BubbleSort(arr,count);cout << "有小到大的排序为:";for (int i = 0; i < count; i++){cout << arr[i]<<" ";}cout << endl;delete[] arr;}




0 0
原创粉丝点击