八大排序算法之三选择排序—简单选择排序(Simple Selection Sort)
2016-09-19 22:52
567 查看
基本思想:
在要排序的一组数中,选出最小(或者最大)的一个数与第1个位置的数交换;然后在剩下的数当中再找最小(或者最大)的与第2个位置的数交换,依次类推,直到第n-1个元素(倒数第二个数)和第n个元素(最后一个数)比较为止。
简单选择排序的示例:
View Code
在要排序的一组数中,选出最小(或者最大)的一个数与第1个位置的数交换;然后在剩下的数当中再找最小(或者最大)的与第2个位置的数交换,依次类推,直到第n-1个元素(倒数第二个数)和第n个元素(最后一个数)比较为止。
简单选择排序的示例:
#include<iostream> using namespace std; const int N =1005; void SelectSort(int a[],int ); void print(int a[],int num); void swap(int &a,int &b); int main() { int s ; int T; cin>>T; while(T--) { int n; cin>>n; for(int j=0;j<n;j++) cin>>s[j]; SelectSort(s,n); print(s,n); cout<<endl; } return 0; } void SelectSort(int arr[],int size) { int minIndex, maxIndex; for (int i = 0; i < size / 2; i++) { minIndex = i; maxIndex = size-i-1; for (int j = i; j < size - i ; j++) { if (arr[j] > arr[maxIndex]) { maxIndex = j; //continue; } if (arr[j] < arr[minIndex]) { minIndex = j; } } if (maxIndex == i && minIndex == size - i - 1) { //特殊交换位置一,当最大的交换位置和最小的交换位置都在最前面和最后面 swap(arr[maxIndex],arr[minIndex]); } else if (maxIndex == i) { //特殊交换位置二,当最大的交换位置是最前面 // Swap(arr[n - i], arr[maxIndex]) swap(arr[size-i-1],arr[maxIndex]); swap(arr[i], arr[minIndex]); } else if (minIndex == size - i - 1) { //特殊交换位置三,当最小的交换位置是最后面 swap(arr[i], arr[minIndex]); swap(arr[size - i-1], arr[maxIndex]); } else { //除了上面三种特殊交换,就剩普通交换了,普通交换随便哪个先交换都行 swap(arr[i], arr[minIndex]); swap(arr[size - i-1], arr[maxIndex]) ; } } } void swap(int &a,int& b)//交换元素 { int temp; temp=a; a=b; b=temp; } void print(int a[],int n)//输出数组元素 { cout<<a[0]; for(int k=1;k<n;k++) { cout<<" "<<a[k]; } }
View Code
相关文章推荐
- 选择排序—简单选择排序(Simple Selection Sort)
- 选择排序—简单选择排序(Simple Selection Sort)
- 选择排序—简单选择排序(Simple Selection Sort)原理以及Java实现
- 数据结构 - 只需选择排序(simple selection sort) 详细说明 和 代码(C++)
- 排序之简单选择排序(Simple Selection Sort)
- 冒泡排序(bubble sort)、直接插入排序(straight insertion sort)、简单选择排序(simple selection sort)
- 3. 选择排序—直接选择排序(Straight Selection Sort)
- 数据结构&算法(PHP描述) 简单选择排序 simple selection sort
- 选择排序—简单选择排序(Simple Selection Sort)
- Simple Selection Sort(简单选择排序)
- PHP实现排序算法----简单选择排序(Simple Selection Sort)
- 数据结构 - 简单选择排序(simple selection sort) 详解 及 代码(C++)
- 【内部排序】六:直接选择排序(Straight Selection Sort)详解与代码
- java实现选择排序(selection_sort)
- 简单选择排序(Simple Selection Sort)的C语言实现
- 笔试算法题(56):快速排序实现之非递归实现,最小k值选择(non-recursive version, Minimal Kth Selection of Quick Sort)
- 直接选择排序(Straight Selection Sort)
- PHP简单选择排序(Simple Selection Sort)算法学习
- 优化的选择排序——SelectionSortSecond
- 简单选择排序(Simple Selection Sort)