我需要在数组的开头对奇数索引的元素进行排序,甚至在数组的末尾对索引进行排序。任何人都可以知道我应该如何处理这个问题? 输入可以是:arr [] = {1,2,3,4,5} 输出应为:arr [] = {1,3,5,2,4}
答案 0 :(得分:0)
你可以在这里找到一个典型的解决方案 `
#include<stdio.h>
void swap(int *a, int *b);
void segregateEvenOdd(int arr[], int size)
{
/* Initialize left and right indexes */
int left = 0, right = size-1;
while (left < right)
{
/* Increment left index while we see 0 at left */
while (arr[left]%2 == 0 && left < right)
left++;
/* Decrement right index while we see 1 at right */
while (arr[right]%2 == 1 && left < right)
right--;
if (left < right)
{
/* Swap arr[left] and arr[right]*/
swap(&arr[left], &arr[right]);
left++;
right--;
}
}
}
/* UTILITY FUNCTIONS */
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int arr[] = {12, 34, 45, 9, 8, 90, 3};
int arr_size = sizeof(arr)/sizeof(arr[0]);
int i = 0;
segregateEvenOdd(arr, arr_size);
printf("Array after segregation ");
for (i = 0; i < arr_size; i++)
printf("%d ", arr[i]);
return 0;
}