1. Adjust the array so that all odd numbers are ahead of even numbers.
Title:
Input an integer array and implement a function to adjust the order of the numbers in the array so that all the odd numbers in the array are in the first half of the array and all the even numbers are in the second half of the array.
#include <stdio.h> void sort(int* a, int sz) { int left = 0; int right = sz - 1; for (left = 0; left != right; left++) { if (a[left]%2 != 0) //Continue as odd from the front continue; else //Otherwise, it is even exchange position { int temp = a[left]; a[left] = a[right]; a[right] = temp; if (a[right]%2 == 0)//Even from the back, fixed j-- right--; left--; } } } int main() { int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int sz = sizeof(a)/sizeof(a[0]); int i; sort(a, sz); for (i = 0; i < sz; i++) { printf("%d ",a[i]); } return 0; }
2. Young's matrix
There is a two-dimensional array. Each row of the array is incremented from left to right, and each column is incremented from top to bottom. Look for the existence of a number in such an array.
The time complexity is less than O(N);
Array:
1 2 3
2 3 4
3 4 5
1 3 4
2 4 5
4 5 6
1 2 3
4 5 6
7 8 9
#include <stdio.h> //Start at the top right int Findnum1(int arr[3][3], int key, int rows, int cols) { int row = 0; int col = cols-1; while (((row >= 0) && (row < rows)) && ((col <= cols-1))) { if (key < arr[row][col]) { col--; } if (key > arr[row][col]) { row++; } if (key == arr[row][col]) { return 1; } } return 0; } //Start from the lower left corner int Findnum2(int arr[3][3], int key, int rows, int cols) { int row = rows-1; int col = 0; while (((col >= 0) && (col < cols)) && (row <= cols-1)) { if (key < arr[row][col]) { row--; } if (key > arr[row][col]) { col++; } if (key == arr[row][col]) { return 1; } } return 0; } int main() { int arr[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 10}; int key = 9; int ret = Findnum1(arr, key, 3, 3); { if (ret == 0) { printf("Non-existent\n"); } else if (ret == 1) { printf("existence\n"); } } return 0; }