Yêu cầu:
– Viết hàm sắp xếp các phần tử chẵn giảm dần. (các phần tử khác trong mảng giữ nguyên vị trí)
Ví dụ:
Dãy số: 1 9 2 4 6 3 5 0 -5 8
Dãy số sau khi sắp xếp: 1 9 8 6 4 3 5 2 -5 0
Thuật toán:
– Dùng thuật toán bubble sort để sắp xếp các số chẵn, các số lẻ giữ nguyên vị trí
Code:
/************************************************************ * Author: VNCODING * History * 2014/10/05 first create VNCODING *************************************************************/ #include "stdio.h" #include "conio.h" #define LEN_MAX 100 // do dai toi da cua mang void sort_even_in_desending_order(int A[], int len); void main() { int arr[LEN_MAX]; int n; int i; do { printf("\nNhap kich thuoc mang: "); scanf("%d", &n); } while (n > LEN_MAX || n <= 0); //Nhap du lieu cho day so for (i = 0; i < n; i++) { printf("\nA[%d] = ", i); scanf("%d", &arr[i]); } // Sap xep theo thu tu giam dan sort_even_in_desending_order(arr, n); printf("\nDay so sau khi sap xep: "); for (i = 0; i < n; i++) { printf("\nA[%d] = %d", i, arr[i]); } getch(); } void sort_even_in_desending_order(int A[], int len) { int i, j; int temp; // Thuat toan bubble sort for (i = 0; i < len - 1; i++) for(j = i+1; j < len; j++) if(A[i] < A[j] && A[i]%2 == 0 && A[j]%2 == 0) { temp = A[j]; A[j] = A[i]; A[i] = temp; } }
Kết quả:
Nhap kich thuoc mang: 7 A[0] = 1 A[1] = 2 A[2] = -4 A[3] = 9 A[4] = 11 A[5] = 0 A[6] = 3 Day so sau khi sap xep: A[0] = 1 A[1] = 2 A[2] = 0 A[3] = 9 A[4] = 11 A[5] = -4 A[6] = 3
Leave a Reply
You must be logged in to post a comment.