E
E
Ening_apps2017-10-26 19:41:42
Algorithms
Ening_apps, 2017-10-26 19:41:42

How to selectively sort an array by insertions?

Good day. The following task is given:
Sort even numbers in an array using the insertion method in descending order, odd ones in ascending order, and leave zeros in their original places. Add. do not use arrays.
Something doesn’t work for me in any way to come up with and implement a solution. Please tell me what can be done. Many thanks in advance for your replies.
Here's what I screwed up.

void sort(int arrLenth, int arr[]){

  int buf, index;

    for (int i = 1; i < arrLenth; i++)
    {
        buf = arr[i];
        index = i - 1;
        while(index >= 0 && arr[index] < buf )
        {
      if(arr[i]%2!=0 && arr[index+1]%2!=0)
        continue;
            arr[index+1] = arr[index];
            index--; 
        }
        arr[index+1] = buf;
    }
  for (int i = 1; i < arrLenth; i++)
    {
        buf = arr[i];
        index = i - 1;
        while(index >= 0 && arr[index] > buf )
        {
      if(arr[i]%2==0 && arr[index+1]%2==0)
        continue;
            arr[index+1] = arr[index];
            index--; 
        }
        arr[index+1] = buf;
    }

  
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2017-10-26
@Ening_apps

#include <stdio.h>

void insertodd(int arr[], int hi) {
    int a = arr[hi];
    for (int lo = hi - 1; lo >= 0; lo--) {
        if (arr[lo] & 1) {
            if (a < arr[lo]) {
                arr[hi] = arr[lo];
                hi = lo;
            } else break;
        }
        arr[hi] = a;
    }
}

void inserteven(int arr[], int hi) {
    int a = arr[hi];
    for (int lo = hi - 1; lo >= 0; lo--) {
        if (arr[lo] && !(arr[lo] & 1)) {
            if (a > arr[lo]) {
                arr[hi] = arr[lo];
                hi = lo;
            } else break;
        }
        arr[hi] = a;
    }
}

void customsort(int arr[], int len) {
    for (int i = 1; i < len; i++) {
        if (arr[i] & 1) insertodd(arr, i);
        else if (arr[i]) inserteven(arr, i);
    }
}

int main() {
    int arr[6] = {1, 2, 5, 3, 0, 4};
    customsort(arr, 6);
    for (int i = 0; i < 6; i++)
        printf("%d, ", arr[i]);
    return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question