【问题标题】:Sort elements by placing elements with odd number index first and even indexes in the end of an array in C [closed]通过将具有奇数索引的元素放在第一位并将偶数索引放在C中的数组末尾来对元素进行排序[关闭]
【发布时间】:2018-05-09 11:13:22
【问题描述】:

我需要对数组开头的奇数索引和数组末尾的偶数索引的元素进行排序。谁能告诉我应该如何处理这个问题? 输入可以是:arr[] = {1, 2, 3, 4, 5} 输出应该是:arr[] = {1, 3, 5, 2, 4}

【问题讨论】:

标签: c arrays sorting indexing


【解决方案1】:

你可以在这里找到一个典型的解决方案 `

 #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; 
   }

`Link for the answer

【讨论】:

  • geeksforgeeks..
  • 是的,他可以在 google 上搜索
猜你喜欢
  • 2020-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 1970-01-01
相关资源
最近更新 更多