who can help to explain what is wrong in my code..counting sort of array in c++ -


here wrote code sorts arrays wrong , dont understand wrong please explain me..

#include <iostream> using namespace std;  void printarray(int array[], int length){      (int = 0; < length; i++)         cout << array[i];     cout << endl; }  /* min , max values first , last elements of array*/ void countingsort(int array[], int length){      int max = array[0];     int min = array[0];     int count[max - min + 1] = {};     int sum = 0;      (int = 0; < length; i++){         if (array[i] > max)             max = array[i];         else             min = array[i];     }     /* new array indexes*/     (int = 0; < max - min + 1; i++){         count[array[i]]++;       }      (int j = 0;j < max - min;j++)     {         while(count[j] --)          array[sum++] = j;                } }  int main() {      int array[] = {4,7,8,9,10,6};     countingsort(array, 6);     printarray(array,6);     return 0; } 

it have sort arrays through indexes

int max = array[0]; 

this sets max first element of array, not last one. when line of code runs:

int count[max - min + 1] = {}; 

count has size of 1.

change to:

int max = array[length - 1]; 

also, c++ not support variable length arrays; there compilers have extended support it. size of array must fixed constant @ time of compilation these compilers. if want use vlas, use std::vector instead.


Comments