(C language) Adjust the order of odd and even numbers so that all odd numbers in the array are located in the first half of the array, and all even numbers are located in the second half of the array.

Enter an integer array and implement a function
to adjust the order of the numbers in the array so that all odd numbers in the array are in the first half of the array, and all even numbers are in the second half of the array.
Problem analysis: It is required that the first half is an odd number and the second half is an even number, so we can find an even number from the left and an odd number from the right, and exchange these two numbers.
Code and comments:

#define  _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
void sortarr(int arr[], int sz){
    
    
	int left = 0;
	int right = sz - 1;
	int tmp = 0;
	while (left<right)
	{
    
    
		if (arr[left] % 2 != 0){
    
    
			left++;
		}
		if (arr[right] % 2 == 0){
    
    
			right--;
		}
		int tmp = arr[left];//遍历的过程中,交换不满足的数据
		arr[left] = arr[right];
		arr[right] = tmp;
	}
}
int main(){
    
    
	int arr[] = {
    
     1, 8, 6, 4, 5, 9, 7, 13 };
	int sz = sizeof(arr) / sizeof(arr[0]);//计算数组长度
	sortarr(arr, sz);//调用void方法
	for (int i = 0; i < sz; i++){
    
    //遍历数组中的每个数
		printf("%d ", arr[i]);//输出重新排序后的数组
	}
	system("pause");
	return 0;
}

Code screenshot:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44436675/article/details/110696084