随机生成长度为10的整型数组,利用插入排序对数组进行排序。
代码如下:
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
//找到后续最小元素
int findSmallestRemainingElement(int arr [], int size, int index){
int index_of_smallest_value = index;
for (int i = index + 1; i < size; i++){
if (arr[i] < arr[index_of_smallest_value]){
index_of_smallest_value = i;
}
}
return index_of_smallest_value;
}
//交换元素
void swap(int arr [], int first_index, int second_index){
int temp = arr[first_index];
arr[first_index] = arr[second_index];
arr[second_index] = temp;
}
//数组排序
void sort(int arr [], int size){
for (int i = 0; i < size; i++){
int index = findSmallestRemainingElement(arr, size, i);
swap(arr, i, index);
}
}
//打印数组
void displayArray(int arr [], int size){
cout << "{";
for (int i = 0; i < 10; i++){
if (i != 0){
cout << ",";
}
cout << arr[i];
}
cout << "}";
}
int main()
{
int arr[10]; //初始化大小为10的数组
srand(time(NULL)); //我种下一颗种子
for (int i = 0; i < 10; i++){
arr[i] = rand() % 100; //终于收货了果实
}
cout << "Original array: "; //输出原始数组
displayArray(arr, 10);
cout << endl;
sort(arr, 10);
cout << "Sorted array: "; //输出排列后数组
displayArray(arr, 10);
cout << endl;
return 0;
}