.h文件//定义为工具类,对整型数组操作 1 #ifndef SortUtil_H
2 #define SortUtil_H
3 class SortUtil
4 {
5 public:
6 static void SelectSort(
int r[],
int n);
7 static void InsertSort(
int r[],
int n);
8 static void BubbleSort(
int r[],
int n);
9 };
10 #endif
1.cpp #include
"SortUtil.h"
2 #include<iostream>
3 using namespace std;
4 void SortUtil::SelectSort(
int r[],
int n)
//关键码//0号单元用作交换暂存单元
5 {
6 //cout << "开始排序" << n<<r[2]<<endl;
7 //
8 int countOne=
0;
9 int countTwo=
0;
10 for(
int i=
1;i<n;i++)
//对n个记录进行n-1次的简单排序
11 {
12 int index=
i;
13 for(
int j=i+
1;j<n;j++)
//在无序区中选择最小的//又是一轮的比较
14 {
15 if (++countOne&&r[j] <
r[index])
16 {
17 index = j;
//主要是指针的变化 记录下最小的一个数
18 }
19 }
20 if(index!=
i)
21 {
22 int temp =
r[i];
23 r[i]=
r[index];
24 r[index] =
temp;
25 countTwo+=
3;
26 }
27 }
28 cout<<
"比较的次数:"<<countOne<<
endl;
29 cout<<
"移动的次数:"<<countTwo<<
endl;
30 }
31 void SortUtil::InsertSort(
int r[],
int n)
32 {
33 int countOne=
0;
34 int countTwo=
0;
35
36 for(
int i=
1;i<n;i++
)
37 {
38 int j =
0;
39 r[
0]=r[i];
//设置哨兵
40 for( j=i-
1;++countOne&&r[
0]<r[j];j--
)
41 {
42 r[j+
1]=
r[j];
43 countTwo++
;
44 }
45 r[j+
1]=r[
0];
//因为在判断前都会执行一次j--,所以要j+1;
46 }
47 cout<<
"比较次数为:"<<countOne<<
endl;
48 cout<<
"移动次数为:"<<countTwo+
2<<endl;
//加上两个赋值语句
49 }
50 void SortUtil::BubbleSort(
int r[],
int n)
51 {
52 int countOne=
0;
53 int countTwo=
0;
54 int exchange=
n;
55 int bound=
exchange;
56 while(exchange!=
0)
57 {
58
59 exchange=
0;
60 for(
int j=
1;j<bound-
1;j++
)
61 {
62 if(++countOne&&r[j]>r[j+
1])
63 {
64 r[
0]=
r[j];
65 r[j]=r[j+
1];
66 r[j+
1]=r[
0];
67 countTwo+=
3;
68 exchange=
j;
69 }
70 }
71 }
72 cout<<
"比较次数为:"<<countOne<<
endl;
73 cout<<
"移动次数为:"<<countTwo<<
endl;
74 }
转载于:https://www.cnblogs.com/lst601z815/p/5034609.html
相关资源:各显卡算力对照表!
转载请注明原文地址: https://win8.8miu.com/read-26487.html