Parity sorting of arrays in C Language
Today, I encountered a problem of implementing the odd/even sorting of arrays. I would like to share with you the solution. Idea 1: Create a new array to traverse the desired array. Put the technology together with an even number and replace it with the content in the array. The Code is as follows:
# Define LEN 10 # include <stdio. h> # include <stdlib. h> int main () {int arr [LEN] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // array initialization int odd [LEN] = {0}; // used to store an odd number of int dou [LEN] = {0}; // used to store an even number of int j = 0; int k = 0; for (int I = 0; I <LEN; I ++) {if (arr [I] % 2) {odd [j] = arr [I]; j ++;} else {dou [k] = arr [I]; k ++ ;}} for (int I = 0; I <LEN; I ++) // Changes to the target array {if (I <= j) {arr [I] = odd [I];} else {arr [I] = dou [I-j-1] ;}} for (int I = 0; I <LEN; I ++) {printf ("% d", arr [I]);} system ("pause"); return 0 ;}
Idea 2: What should we do if we do not allow the creation of new space variables? We can solve this problem with the idea of Bubble sorting. If this number is odd, we can bubble it to the top of the bubble array, and then get the answer. The implementation code is as follows:
# Include <stdio. h> int * doubleline (int * a, int size) // The function encapsulated by the bubble sort to implement parity sorting {int I = 0; for (I = 0; I <size; I ++) // bubble process {for (int j = 0; j <size-I-1; j ++) {if (* (a + j) % 2) = 0) {int tmp = * (a + j); * (a + j) = * (a + j + 1 ); * (a + j + 1) = tmp ;}} return a ;}int main () // debugging process {int arr [] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; int size = sizeof (arr)/sizeof (int ); // obtain the array size int * p = doubleline (arr, size); for (int I = 0; I <size; I ++) {printf ("% d ", * (p + I);} system ("pause"); return 0 ;}
I personally think that although Bubble Sorting saves space, the efficiency of doing so is extremely low when the array is very large, and I hope to consider it when using it. I hope to criticize and correct any shortcomings.