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
廣告