dimanche 28 décembre 2014

Insertion Sort program

(A little background so you don't hate on me, my deepest apologies if this post is redundant or too basic for this forum) -


I am a High school student and a beginner and who's just started learning c++ recently and while I was learning arrays, I came across the insertion sort algorithm. It was pretty confusing to understand at first but after watching a couple of videos I tried making my own version of it.


The program itself is very simple: I ask the user for the array's size and then the elements. Then I want to sort the elements in ascending order but the problem is, the output isn't quite what I expect.


So when a user enters something like [4,2,1,3], instead of printing [1,2,3,4], I see [1,1,2,3]! The program has just one function which just prints the array and adds a comma to every element except the last one. Please do not close this thread as I've searched long and couldn't find something similar and once again I'm very sorry if this is redundant.



#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

void DisplayArray (int size, int array[]) {
for (int k=0; k< size; k++) {
if (k!=size-1) {
cout << array[k] << ", ";
}
else {
cout << array[k] << ".";
}
}
}

int main(int argc, const char * argv[]) {
int size;
cin >> size;
int array[size-1];
for (int j=0; j< size; j++) {
cin >> array[j];
}


for (int i =1; i<size; i++) {
int value = array[i];
int m = i - 1;

while (m >= 0){
if (value < array[m]) {
array [i] = array[m];
array [m] = value;
m = m - 1;
}
else {
break;
}
}

}

DisplayArray(size, array);


}

Aucun commentaire:

Enregistrer un commentaire