C++ 程序实现选择排序
在选择排序技术中,将列表分为两部分。一部分中的所有元素都已排序,另一部分中的项目未排序。首先,我们从数组中获取最大值或最小值。在获取数据(如最小值)后,我们通过将第一个位置的数据替换为最小数据,将其放入列表的开头。执行后,数组将变小。因此,这种排序技术得以完成。
选择排序技术的时间复杂度
时间复杂度:O(n2)
空间复杂度:O(1)
Input − The unsorted list: 5 9 7 23 78 20 Output − Array after Sorting: 5 7 9 20 23 78
算法
selectionSort(array, size)
输入:一个数据数组和数组中的总数
输出:已排序的数组
Begin for i := 0 to size-2 do //find minimum from ith location to size iMin := i; for j:= i+1 to size – 1 do if array[j] < array[iMin] then iMin := j done swap array[i] with array[iMin]. done End
示例代码
#include<iostream>
using namespace std;
void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void selectionSort(int *array, int size) {
int i, j, imin;
for(i = 0; i<size-1; i++) {
imin = i; //get index of minimum data
for(j = i+1; j<size; j++)
if(array[j] < array[imin])
imin = j;
//placing in correct position
swap(array[i], array[imin]);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
selectionSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}输出
Enter the number of elements: 6 Enter elements: 5 9 7 23 78 20 Array before Sorting: 5 9 7 23 78 20 Array after Sorting: 5 7 9 20 23 78
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP