码迷,mamicode.com
首页 > 编程语言 > 详细

七大排序之冒泡排序

时间:2020-05-26 20:25:46      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:using   const   ios   gets   冒泡排序   aos   --   cout   swa   

经典冒泡排序:

思想:俩俩比较,如果是实现升序排序,则俩俩排序的目的就是将其中大的数依次往后挪,或者是将较小的数往前挪;

    每一趟外循环的目的就是将这一趟中最大的数放在数组的最后面,或者是将最小的数放在最前面。

 

例如:3 4 2 5 0 1  六个数,我们采用大数沉底的方法。

【1】先说外循环:即趟数

第一趟循环将5放到数组的最后一位,第二趟将4放在5的前面,依次这样,最后第五趟1放在第二位置,此时0就已经排在最前面了,所以外循环总共要循环(n-1)次;n为数的个数。所以外循环变量i为:for(i=0;i<n-1;i++)

【2】再说内循环:即具体实现将大树依次放到数组的最后

数组的第1位下标为0,所以初始化内循环变量j=0,在第一轮外循环中,需要将5放在最后,从下标为0开始,即第一位开始和第二位进行比较,3<4,后面的数大,不用交换,再将j++,比较第二位和第三位4>2交换位置得到(324501);再次j++,比较第三位和第四位4<5不交换,j++比较第四位和第五位5>0交换得到(324051)j++比较第五位和第六位

5>0,交换的到(324015)所以在第一趟中将最大数字5沉底。总共j++执行了5次(n-i-1)次(注意j是从0开始的)。

所以内循环变量为:for(int j=0;j<n-i-1;j++)。

整体代码如下:

 1 #include<iostream>
 2 #include<time.h>
 3 #include<stdlib.h>
 4 #include<sys/timeb.h>
 5 using namespace std;
 6 
 7 const int Max = 10;
 8 
 9 void swap(int& a, int& b) {
10     int temp = a;
11     a = b;
12     b = temp;
13 }
14 //小数冒泡
15 //void Maopaosort(int* arr,int length) {
16 //    for (int i = 0; i < length-1; i++) {
17 //        for (int j = length-1; j>i; j--) {     
18 //            if (arr[j-1] > arr[j]) 
19 //                swap(arr[j], arr[j - 1]);
20 //        }
21 //    }
22 //}
23 //大数沉底
24 
25 void Maopaosort(int* arr, int length) {
26     for (int i = 0; i < length-1; i++) {
27         for (int j = 0; j<length-i-1; j++) {
28             if (arr[j] > arr[j+1])
29                 swap(arr[j], arr[j +1]);
30         }
31     }
32 }
33 
34 
35 long getSystemTime() {
36     struct timeb tb;
37     ftime(&tb);
38     return tb.time * 1000 + tb.millitm;
39 }
40 void Print(const int* arr,int length){
41     for (int i = 0; i < length; i++) {
42         cout << arr[i] << " ";
43     }
44 
45 }
46 int main() {
47     int arr[Max];
48     srand((unsigned)time(NULL));
49     for (int i = 0; i < Max; i++) {
50         arr[i] = rand() % Max;
51     }
52     cout << "排序前:\n";
53     Print(arr,Max);
54     long pt = getSystemTime();
55     Maopaosort(arr, Max);
56     long at = getSystemTime();
57     cout << "\n排序后:\n";
58     Print(arr,Max);
59 
60     cout << "\ntime of sort:" << at - pt << "ms\n";
61 
62 
63     return 0;
64 }

 

七大排序之冒泡排序

标签:using   const   ios   gets   冒泡排序   aos   --   cout   swa   

原文地址:https://www.cnblogs.com/jibisheng/p/12968163.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!