lundi 19 octobre 2020

Why this code not showing correct output? This question is for sorting of array that contains 0's, 1's & 2's without any sorting algorithm. Help me

wrote this code without using any sort function... Just swapped the values.. The algo used here is DANISH
FLAG ALGORITHM.. AND WHEN I INPUT MORE THAN 5 NUMBERS IT DOESN'T DISPLAY ANYTHING. AND IF I TAKE SMALL VALUES IT DOESN'T PRINT THE VALUE 2.

#include<iostream>

#include<algorithm>

using namespace std;
void sorted(int * arr, int n) //sort function
{
    int * low = arr;
    int * mid = arr;
    int * high;
    for (int i = 0; i < n; i++) {
        if (i == n - 1)
            high = (arr + i);
    }
    while (mid <= high) {
        if ( * mid == 0) {
            int temp;
            temp = * low;
            * low = * mid;
            * mid = temp;
            mid++;
            low++;
        }
        if ( * mid == 1) {
            mid++;
        }
        if ( * mid == 2) {
            int temp2;
            temp2 = * mid;
            * mid = * high;
            * high = * mid;
            high--;
        }
    }
}

void printarr(int * arr, int n) {
    for (int i = 0; i < n; i++)
        cout << * (arr + i);
}

int main() {
    int n;
    cin >> n;
    int * arr = new int(n);
    for (int i = 0; i < n; i++)
        cin >> * (arr + i);
    sorted(arr, n);
    printarr(arr, n);
    delete[] arr;
    return 0;
}

OUTPUT

5 1 0 1 2 0 00110

instead of 00112

Aucun commentaire:

Enregistrer un commentaire