C++ 中的替代排序
按照这样的方式对一个整数数组的元素进行排序,第一个元素为数组最大值,排序后的数组的第二个元素为最小值,第三个元素为次小值,第四个元素为数组的次大值,依此类推。
我们举个例子来更好地理解这个概念,
Input : 4 1 8 2 9 3 7 Output : 9 1 8 2 7 3 4 Explanation : The elements in a sorted way is 1 2 3 4 7 8 9. Now, let’s create it in the manner we wanted it i.e. alternate sorted form. So, the largest element of the array first i.e. 9 followed by 1 which is the smallest element of the array i.e. 1 next comes 8 , 2 , 7 , 3, 4.
既然我们已经理解了这个概念,我们就可以针对此问题制定一个解决方案。因此,一个可能的解决方案是对数组进行排序,然后打印这个排序后数组的第一个和最后一个元素。我们基于此解决方案创建一个算法。
算法
Step 1 : Sort the array. Step 2 : Create two pointers one for traversing from start and other pointer for traversing from end. Step 3 : Print values of the pointer in alternate form and increase the value of the iterator.
示例
#include <iostream>
using namespace std;
void alternateSort(int arr[], int n) ;
void swap(int *xp, int *yp) ;
void selectionSort(int arr[], int n) ;
int main(){
int arr[] = { 4,1,8,2,9,3,7};
int n = sizeof(arr)/sizeof(arr[0]);
alternateSort(arr, n);
return 0;
}
void alternateSort(int arr[], int n){
selectionSort(arr, n);
int i = 0, j = n-1;
while (i < j) {
cout << arr[j--] << " ";
cout << arr[i++] << " ";
}
if (n % 2 != 0)
cout << arr[i];
}
void swap(int *xp, int *yp){
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n){
int i, j, min_idx;
for (i = 0; i < n-1; i++){
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
}输出
9 1 8 2 7 3 4
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP