梦幻西游手游宝宝获得:帮忙用C++编个排序的程序

来源:百度文库 编辑:高考问答 时间:2024/04/28 23:44:05
排出来追加50分
要求在同一个程序里实现:
实验题:已知数据如下,10 9 15 30 25 11 2 3 1 50
用直接选择排序法,和直接插入排序法;冒泡排序法,分别实现数据由大到小排序,并打印每趟排序结果。

#include <iostream.h>
const int MAX = 10;

void Swap(int &a, int &b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
}
void Write(int array[], int begin, int end)
{
for(int loopCount = begin; loopCount <= end; loopCount ++)
cout << array[loopCount] << " ";
cout << endl;
}

void InsertionSort(int array[], int begin, int end)
{
int i, j;
int tmp;
for(i = begin+1; i <= end; i ++)
{
tmp = array[i];
for(j = i-1; j >= begin; j --)
{
if(tmp > array[j])
array[j + 1] = array[j];
else
break;
}
array[j+1] = tmp;
Write(array, begin, end);
}
}

void SelectionSort(int array[], int begin, int end)
{
int i, j;
int position;
for(i = begin; i < end; i ++)
{
for(j = i+1, position = i; j <= end; j ++)
{
if(array[j] > array[position])
position = j;
}
Swap(array[i], array[position]);
Write(array, begin, end);
}
}

void BubbleSort(int array[], int begin, int end)
{
int i, j;
for(i = begin; i < end; i ++)
{
for(j = begin; j <= end - begin -1; j ++)
{
if(array[j] < array[j+1])
Swap(array[j], array[j+1]);
}
Write(array, begin, end);
}
}

bool Copy(int array1[], int array2[], int n1, int n2)
{
if(n1 != n2)
return false;
else
{
for(int loopCount = 0; loopCount < n1; loopCount ++)
{
array1[loopCount] = array2[loopCount];
}
return true;
}
}

int main()
{
int number, loopCount;
int initinal[MAX], sort[MAX];

number = 10;
for(loopCount = 0; loopCount < number; loopCount ++)
cin >> initinal[loopCount];

cout << "Insertionsort:" << endl;
Write(initinal, 0, number-1);
Copy(sort,initinal,number, number);
InsertionSort(sort,0,number-1);
cout << endl;

cout << "Selectionsort:" << endl;
Write(initinal, 0, number-1);
Copy(sort,initinal,number, number);
SelectionSort(sort,0,number-1);
cout << endl;

cout << "Bubblesort:" << endl;
Write(initinal, 0, number-1);
Copy(sort,initinal,number, number);
BubbleSort(sort,0,number-1);
cout << endl;
return 0;
}
有这100我就1000了!

JAVA写的,你改成C++就行了
为了100分,浪费我10分钟

public void bubbleSort(int a[]) { //数组的冒泡排序
int n = a.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}

public void selectSort(int a[]) { //数组的选择排序
for (int n = a.length; n > 1; n--) {
int i = max(a, n);
int temp = a[i];
a[i] = a[n - 1];
a[n - 1] = temp;
}
}

书上不都有么