Why doesn't this C++ insertion sort work? - c++

I'm learning C++ and this is one of my first programs that is going to sort a list of numbers, I found the algorithm in Kenneth H. Rosen book and wrote it in C++. when I check it on the paper it seems to be correct, but in practice it has some error. For example I enter 3(enter)2(enter)1(enter)4(enter)5(enter) and it returns 3 1 1 4 5 as the answer. I don't know what is the problem, please help.
int main()
{
int i, j, s, n, k, a[50];
cout << "Enter number of numbers:\n";
cin >> n;
cout << "Enter the numbers:\n";
for (i = 0; i < n; i++) {
cin >> a[i];
}
for (j = 2; j < n; j++) {
i = 1;
while (a[j] > a[i]) {
i = i + 1; // Here we find the proper place to(if needed) directly insert our number into the sorted part.
}
s = a[j];
for (k = 0; k < j - i - 1; k++) {
a[j - k] = a[j - k - 1];
}
a[i] = s;
}
for (i = 0; i < n; i++) {
cout << a[i] << " ";
}
_getch();
return 0;
}
I've also included the header files and namespace, not written here though. And in the case you think I have used so many variables, sorry about that, I needed them :)

Your index i should start from the first element which is 0 instead of 1.
Fixing line 11 should do the job:
for (j = 2; j < n; j++) {
i = 0;
while (a[j] > a[i]) {
Edit:
Oh, and also, your variable j should start from the second element which is index 1 instead of 2:
for (j = 1; j < n; j++) {

Related

Counting Sort in C++

I am trying to implement the Counting Sort in C++ without creating a function. This is the code that I've written so far, but the program doesn't return me any values. It doesn't give me any errors either. Therefore, what is wrong?
#include <iostream>
using namespace std;
int main()
{
int A[100], B[100], C[100], i, j, k = 0, n;
cin >> n;
for (i = 0; i < n; ++i)
{
cin >> A[i];
}
for (i = 0; i < n; ++i)
{
if (A[i] > k)
{
k = A[i];
}
}
for (i = 0; i < k + 1; ++i)
{
C[i] = 0;
}
for (j = 0; j < n; ++j)
{
C[A[j]]++;
}
for (i = 0; i < k; ++i)
{
C[i] += C[i - 1];
}
for (j = n; j > 0; --j)
{
B[C[A[j]]] = A[j];
C[A[j]] -= 1;
}
for (i = 0; i < n; ++i)
{
cout << B[i] << " ";
}
return 0;
}
It looks like you're on the right track. You take input into A, find the largest value you'll be dealing with and then make sure you zero out that many values in your C array. But that's when things start to go wrong. You then do:
for (i = 0; i < k; ++i)
{
C[i] += C[i - 1];
}
for (j = n; j > 0; --j)
{
B[C[A[j]]] = A[j];
C[A[j]] -= 1;
}
That first loop will always go out of bounds on the first iteration (C[i-1] when i=0 will be undefined behavior), but even if it didn't I'm not sure what you have in mind here. Or in the loop after that for that matter.
Instead, if I were you, I'd create an indx variable to keep track of which index I'm next going to insert a number to (how many numbers I've inserted so far), and then I'd loop over C and for each value in C, I'd loop that many times and insert that many values of that index. My explanation may sound a little wordy, but that'd look like:
int indx = 0;
for(int x = 0; x <= k; x++) {
for(int y = 0; y < C[x]; y++) {
B[indx++] = x;
}
}
If you replace the two loops above with this one, then everything should work as expected.
See a live example here: ideone

Why does the for loop in selection sort have n-1 steps instead of n? C++

I have the following attempt to write a selection sort in C++:
#include <iostream>
using namespace std;
int main()
{
int a[10], k, i, j, n, aux;
cin >> n;
for (i = 0; i <= n-1; i++)
cin >> a[i];
k = a[0];
for (i = 0; i <= n - 2; i++) {
for (j = i + 1; j <= n-1; j++)
if (k > a[j])
k = a[j];
for (j = i + 1; j <= n-1; j++)
if (k == a[j]) {
aux = a[i];
a[i] = a[j];
a[j] = aux;
}
k = a[i + 1];
}
for (i = 0; i <= n-1; i++)
cout << a[i];
return 0;
}
From my tests it returns sorted arrays, so I think it's correct.
But I also have to explain why the main for loop of the sort only takes n-1 steps instead of n. Could anyone explain the "why" part to me?
Consider how many steps are required if n is 1.
Basically, you don't need to sort the first element.
The sorting is done by comparing pairs of elements.
How many pairs are there in an array of N elements? (hint: N-1)
This animation might help explain how the algorithm works.

Insert Sort not working

I am learning sorting algorithms. I googled the insert sort code and when I tried it on my own it's not working out. Can someone please find the error in my code?
#include<iostream>
using namespace std;
int main()
{
int i,size, a[40], key;
cout << "Enter size: ";
cin >> size;
for(int o=0; o<size; o++)
{
cin >> a[o];
}
//insertion sort
for(int j = 1; j <= size-1; j++)
{
key = a[j];
i = j-1;
while((key < a[i]) && (i >= 0));
{
a[i + 1] = a[i];
i = i - 1;
}
a[i + 1] = key;
}
cout << "\nSorted list is as follows\n";
for(int o = 0; o < size; o++)
{
cout << endl << a[o];
}
}
while((key<a[i])&&(i>=0));
You have an infinite while loop here. The semi colon at the end means that the while loop body is empty. Hence i is never decremented and the loop runs forever.
Also, you need to check if the index is valid (i >= 0) before trying to access it's value.
So change the line as below.
while((i >= 0) && (key < a[i]))

Finalize the magic square generator

This code that runs only for odd N. The problem is that there are no ideas how to add support for even values N
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
setlocale(0, "");
int n;
cout << "Enter the size of the magic square - ";
cin >> n;
int **matrix = new int *[n];
for (int i = 0; i < n; ++i)
{
matrix[i] = new int[n];
}
int nsqr = n * n;
int i = 0, j = n / 2;
for (int k = 1; k <= nsqr; ++k)
{
matrix[i][j] = k;
i--;
j++;
if (k % n == 0)
{
i += 2;
--j;
}
else
{
if (j == n)
{
j -= n;
}
else if (i < 0)
{
i += n;
}
}
}
cout << "\n\nMagic square size - " << n << "\n\n";
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << matrix[i][j] << "\t";
}
cout << endl;
}
for (i = 0; i < n; i++)
delete[] matrix[i];
delete[] matrix;
system("pause >> null");
return 0;
}
I would be grateful for tips on troubleshooting.
If i'm not mistaken, the problem is in this line:
int i = 0, j = n / 2;
But i don't know how to change the code to support even values
I would assume that you meant normal magic square (where the number are restricted to 1,2..n^2)
First of all, it's impposible to construct such magic square for n=2.
2nd, you would need an whole new algorithm for it, which is much more complicated. The problem (constructing magic square for any even number) is solved in this paper and while there isn't any psaudo code there, the implementation from the explenation is quite straightforward (long one though).
the problem is here:
i = 0;
int j = n / 2;
for (int k = 1; k <= nsqr; ++k)
{
matrix[i][j] = k;
i--;
}
look how you decrement i inside the loop and making it as an index of the array so:
matrix[-3][j] = k; // will be in your code
you are messing deliberately with the indexes of the array
I found answer on my question in this artcile
I made full revision my algorithm based on this article. Later posted listing the resulting program

Insertion sort task

I was trying to solve a problem in which I should sort increasingly array of numbers, than take first k numbers from sorted array and eliminate those numbers that are repeating and write them on the output.
This is my code:
#include <iostream>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
int tab[n];
for (int i = 0; i < n; i++) //taking n numbers from input
{
cin >> tab[i];
}
int j, element;
for (int i = 1; i < n; i++) //i am using insertion sort
{
j = 0;
while (tab[j] < tab[i])
j++;
element = tab[i];
for(int k = i - 1; k >= j; k--)
tab[k + 1] = tab[k];
tab[j] = element;
}
for (int i = 0; i < k; i++) //writing k smallest numbers without repetitions
{
if (tab[i] == tab[i + 1])
continue;
cout << tab[i] <<"\n";
}
cin >> n;
return 0;
}
generally it works and it gives expected output, however when I am uploading this problem to check its correctness (i found this problem on polish site), it says "wrong anwser".
I cannot see any errors here, maybe you will see something which I wrote bad.
I think you misunderstood the problem. 'eliminate those numbers that are repeating' means you have to print the number once and eliminate subsequent occurrence(s) of that number. For ex.
n = 5;
k = 3;
tab[n] = 5 1 1 1 1
Here, sorted tab[] becomes '1 1 1 1 5', then expected output is '1', but your program gives nothing!
I hope this helps :)