c++实现的四种排序算法

常用的四种排序算法:
冒泡,选择,插入,归并。

include

using namespace std;

void bubbleSort(int[], int);
void insertSort(int[], int);
void selectSort(int[], int);
void mergeSort(int[], int, int, int[]);
int main(){
int number = 0;
cout << “enter the number of elements in tht array: “;
cin >> number;
int arr[100];
int functionSelect = 0;
cout << “type in elements into the array: ” << endl;
for (int i = 0; i < number; i++){
cin >> arr[i];
}
cout << “menu*” << endl;
cout << “bubble sort: 1” << endl;
cout << “insertion sort: 2” << endl;
cout << “selection sort: 3” << endl;
cout << “merge sort: 4” << endl;
cout << “Enter your option: “;
cin >> functionSelect;
switch (functionSelect)
{
case 1:
bubbleSort(arr, number);
cout << “Bubble Sort Result:” << endl;
for (int i = 0; i < number; i++){
cout << “arr[” << i << “] = ” << arr[i] << endl;
}
break;
case 2:
insertSort(arr, number);
cout << “Insert Sort Result:” << endl;
for (int i = 0; i < number; i++){
cout << “arr[” << i << “] = ” << arr[i] << endl;
}
break;
case 3:
selectSort(arr, number);
cout << “Select Sort Result:” << endl;
for (int i = 0; i < number; i++){
cout << “arr[” << i << “] = ” << arr[i] << endl;
}
break;
case 4:
int sorted[100];
mergeSort(arr, 0, number, sorted);
cout << “Merge Sort Result:” << endl;
for (int i = 0; i < number; i++){
cout << “arr[” << i << “] = ” << sorted[i] << endl;
}
break;
default:
break;
}
return 1;
}

void bubbleSort(int arr[], int number){
int temp = 0;
for (int i = 0; i < number; i++){
for (int j = 0; j < number - i - 1; j++){
if (arr[j] > arr[j + 1]){
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

void insertSort(int arr[], int number){
int temp = 0;
int j = 0;
for (int i = 1; i < number; i++){
if (arr[i - 1] > arr[i]){
temp = arr[i];
j = i;
while (j > 0 && arr[j - 1] > temp){
arr[j] = arr[j - 1];
j–;
}
arr[j] = temp;
}
}
}

void selectSort(int arr[], int number){
int index = 0;
int temp;
for (int i = 0; i < number - 1; i++){
index = i;
for (int j = i + 1; j < number; j++){
if (arr[j] < arr[index]){
index = j;
}
}
if (index != i){
temp = arr[index];
arr[index] = arr[i];
arr[i] = temp;
}
}
}

void merge(int arr[], int first, int mid, int last, int sorted[])
{
int i = first, j = mid;
int k = 0;
while (i < mid && j < last)
if (arr[i] < arr[j])
sorted[k++] = arr[i++];
else
sorted[k++] = arr[j++];

while (i < mid)
    sorted[k++] = arr[i++];
while (j < last)
    sorted[k++] = arr[j++];

for (int v = 0; v < k; v++)
    arr[first + v] = sorted[v];

}

void mergeSort(int arr[], int first, int last, int sorted[])
{
if (first + 1 < last)
{
int mid = (first + last) / 2;
mergeSort(arr, first, mid, sorted);
mergeSort(arr, mid, last, sorted);
merge(arr, first, mid, last, sorted);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值