实验二 排序算法
一、要求完成时间
实验开始后的第三周之前完成
二、 实验目的
掌握各种排序方法的实现思想。
三、 实验内容
- 输入1-20个不为零的正整数,遇到0代表输入结束,0不参与排序。
- 数字选择排序方法,1-Bubble Sort,2-Insert Sort,3-Radix Sort(注意大小写要区分)。
- 基数排序能够仅仅实现小于10的正整数的排序。如果输入的数据有大于9数据,基数排序不在排序,直接输出一个0结束程序。
- 使用所选排序方法的排序,结果输出所用方法以及结果,每个数之间用“,”隔开,中间不要有空格。
- 输入输出请严格按下面要求的格式实现,不能少任何一行文字。
四、 特别提醒:运行结果不稳定的原因
这个实验的程序容易出现运行结果不稳定情况,也容易出现死循环或者不正常退出的情况,造成的原因大多是使用的非法内存,也就是数组变量越界引用,例如下面的引用就会造成非法引用。
int opStack[100];
Int I=0;
Int c;
…………如果你程序逻辑错误,运行到这个位置时c=101
opStack[c]=123; //这个时候opstack没有101数据,结果就操作了opstack数组后面的非法内存,如果这个位置正好是程序,那就造成严重错误,如果是别的变量,比如是变量I的位置,那就造成i=123了,这样的结果必然是错误的。
还有一种情况就是数组没有赋初值,然后直接引用了,没有赋初值,数组里面的数据不一定是0,可能是大于0的数据。
#include <iostream>
using namespace std;
//1-Bubble Sort
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void printArray(int array[], int length)
{
for (int i = 0; i < length; i++) {
if (i == 0) {
cout << array[i];
}
else {
cout << "," << array[i];
}
}
cout << endl;
}
//及时终止的冒泡排序
void BubbleSort(int a[], int n) {
bool sorted = false;
for (int i = 1; i < n && !sorted; i++) {//控制进行冒泡的次数,冒n-1次
sorted = true;
for (int j = 0; j < n - i; j++) {
if (a[j + 1] < a[j]) {
swap(a[j], a[j + 1]);
sorted = false;
}
}
}
}
//2-Insert Sort
void insert(int a[], int n, const int x) {
int i = 0;
for (i = n - 1; i >= 0 && x < a[i]; i--) a[i + 1] = a[i];
a[i + 1] = x;
}
void insertSort(int a[], int n) {
for (int i = 1; i < n; i++) {
int t = a[i];
insert(a, i, t);
}
}
//3-Radix Sort
//基数排序
bool Radix(int a[], int n) {
for (int i = 0; i < n; ++i) {
if (a[i] > 9) {
cout << "Radix Sort" << endl;
cout << "0" << endl;
return false;
}
}
int box[10][20];//定义二维数组,并赋初值
for (int k = 0; k < 10; ++k) {
for (int i = 0; i < 20; ++i) {
box[k][i] = -1;
}
}
for (int j = 0; j < n; ++j) {
int t = 0;
while (box[a[j]][t] != -1) {
t++;//相同基数的数字也能正常排序
}
box[a[j]][t] = a[j];
}
int num = 0;
for (int l = 0; l < 10; ++l) {
for (int i = 0; i < 20; ++i) {
if (box[l][i] != -1) {
a[num] = box[l][i];
num++;
}
else {
break;
}
}
}
cout << "Radix Sort" << endl;
printArray(a, n);
return true;
}
int main() {
int *list;
list = new int[20];
int len = 0;
cout << "Input" << endl;
cin >> list[len];
while (list[len] != 0) {
len = len + 1;
cin >> list[len];
}
cout << "1-Bubble Sort,2-Insert Sort,3-Radix Sort" << endl;
//输入所选择的排序方法
int choice;
cin >> choice;
cout << "Output" << endl;
if (choice == 1) {
BubbleSort(list, len);
cout << "Bubble Sort" << endl;
printArray(list, len);
}
else if (choice == 2) {
insertSort(list, len);
cout << "Insert Sort" << endl;
printArray(list, len);
}
else if (choice == 3) {
Radix(list, len);
}
cout << "end0";
return 0;
}