Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // FOLLOW GITHUB: https://github.com/ivandrofly
- namespace CustomSortArrayEvenOdd
- {
- using System;
- class Program
- {
- static void Main(string[] args)
- {
- int[] data = { 1, 2, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 0, 0, 0, 10, 12, 27, 27, 20 };
- //Sort(data);
- SortRecursion(data, 0, data.Length - 1);
- Print(data);
- Console.ReadLine();
- }
- // solution #1
- private static void Sort(int[] data)
- {
- int evenIdx = data.Length - 1;
- for (int i = 0; i < data.Length; i++)
- {
- if (data[i] % 2 != 0 && i < evenIdx)
- {
- int oddIdx = i;
- while (data[evenIdx] % 2 != 0 && oddIdx < evenIdx)
- {
- evenIdx--;
- }
- if (data[evenIdx] % 2 == 0)
- {
- Swap(data, evenIdx, oddIdx);
- }
- }
- }
- BubbleSort(data, 0, evenIdx - 1);
- BubbleSort(data, evenIdx, data.Length);
- }
- // solution #2:
- private static void SortRecursion(int[] data, int oddFrom, int evenFrom)
- {
- int oddIdx = FindOdd(data, oddFrom, evenFrom);
- int evenIdx = FindEven(data, oddIdx, evenFrom);
- if (oddIdx != -1 && evenIdx != -1)
- {
- Swap(data, evenIdx, oddIdx);
- SortRecursion(data, oddIdx + 1, evenIdx - 1);
- }
- }
- private static int FindOdd(int[] data, int oddIdx, int evenIdx)
- {
- if (oddIdx == -1 || evenIdx == -1)
- {
- return -1;
- }
- for (int i = oddIdx; i < evenIdx; i++)
- {
- if (data[i] % 2 != 0)
- {
- return i;
- }
- }
- return -1;
- }
- private static int FindEven(int[] data, int oddIdx, int evenIdx)
- {
- if (oddIdx == -1 || evenIdx == -1)
- {
- return -1;
- }
- for (int i = evenIdx; i > oddIdx; i--)
- {
- if (data[i] % 2 == 0)
- {
- return i;
- }
- }
- return -1;
- }
- private static void Print(int[] data)
- {
- for (int i = 0; i < data.Length; i++)
- {
- if (i < data.Length - 1)
- {
- Console.Write(data[i] + ", ");
- }
- else
- {
- Console.Write(data[i]);
- }
- }
- }
- private static void Swap(int[] data, int i, int j)
- {
- int temp = data[i];
- data[i] = data[j];
- data[j] = temp;
- }
- public static void BubbleSort(int[] data, int from, int to)
- {
- // [2,4,6,2,2,2,1,1,1,1,1,1]
- for (int i = from; i < to; i++)
- {
- for (int j = from; j < to - (i - from) - 1; j++) // -1 for the j+1 in comparision
- {
- if (data[j] > data[j + 1])
- {
- Swap(data, j, j + 1);
- }
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement