在解決一些問題時,以適當的形式排列資料項是一項重要的任務。
efficient way. The element sorting problem is one of the most commonly discussed 排列問題。在本文中,我們將看到如何排列數組元素 按照它們的值降序排列(在C 中)。在這個領域中有許多不同的排序演算法用於對數字或非數字進行排序
# 按給定順序的元素。在本文中,我們將只介紹兩種簡單的方法 sorting. The bubble sort and the selection sort. Let us see them one by one with proper 演算法和C 實作程式碼。冒泡排序技術是一種最常見且較簡單的排序方法。
數組中的元素。此方法檢查兩個相鄰的元素,如果它們是正確的 order, then skip to the next elements, otherwise interchange them to place them in correct 將其它元素順序排列,然後跳過到下一個元素,否則交換它們以將其放置在正確位置 order. Then move towards right and do the same for the other pair of values. The bubble 按順序排列。然後向右移動,並對另一對值執行相同操作。氣泡 排序技術有幾個階段,在每個階段結束時,一個元素被放置在 正確的預期位置。讓我們來看看冒泡排序技術的演算法。#include <iostream> using namespace std; void display( int arr[], int n ){ for ( int i = 0; i < n; i++ ) { cout << arr[i] << ", "; } } void swap ( int &a, int &b ){ int temp = a; a = b; b = temp; } void solve( int arr[], int n ){ int i, j; for ( i = 0; i < n; i++ ) { for ( j = 0; j < n-1; j++ ) { if ( arr[j] < arr[ j+1 ] ) { swap( arr[j], arr[ j + 1 ] ); } } } } int main(){ int arr[] = {8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12, 89, 95, 63, 84}; int n = sizeof( arr ) / sizeof( arr[0] ); cout << "Array before sorting: "; display(arr, n); solve( arr, n ); cout << "\nArray After sorting: "; display(arr, n); }
Array before sorting: 8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12, 89, 95, 63, 84, Array After sorting: 96, 95, 89, 84, 78, 74, 63, 58, 45, 44, 36, 25, 12, 12, 10, 8, 5, 2,
#include <iostream> using namespace std; void display( int arr[], int n ){ for ( int i = 0; i < n; i++ ) { cout << arr[i] << ", "; } } void swap ( int &a, int &b ){ int temp = a; a = b; b = temp; } int max_index( int arr[], int n, int s, int e ){ int max = 0, max_ind = 0; for ( int i = s; i < e; i++ ) { if ( arr[i] > max ) { max = arr[i]; max_ind = i; } } return max_ind; } void solve( int arr[], int n ){ int i, j, ind; for ( i = 0; i < n; i++ ) { ind = max_index( arr, n, i, n ); if ( arr[i] < arr[ ind ] ) { swap( arr[i], arr[ ind ] ); } } } int main(){ int arr[] = {8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12,89, 95, 63, 84}; int n = sizeof( arr ) / sizeof( arr[0] ); cout << "Array before sorting: "; display(arr, n); solve( arr, n ); cout << "\nArray After sorting: "; display(arr, n); }
Array before sorting: 8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12, 89, 95, 63, 84, Array After sorting: 96, 95, 89, 84, 78, 74, 63, 58, 45, 44, 36, 25, 12, 12, 10, 8, 5, 2,
以上是C++程式:將陣列元素依降序排序的詳細內容。更多資訊請關注PHP中文網其他相關文章!