I am learning c++ but I am following a terrible book which was recommended to me at school. It has many errors but I found a blunder where the logic of the program is wrong. Could you please check if this is really a an error or I am understanding it wrong?
According to the book code for bubble sort is as follows -
#include <iostream.h>
main()
{
int num, i, j, temp;
cin >> num;
int item[num];
for (i = 0; i < num; i++)
cin >> item[i];
for (i = 0; i < num -1; i++)
for ( j = i+1; j < num; j++)
if (item[i] > item[j]){
temp = item[i];
item[i] = item[j];
item[j] = temp;
}
what I think - I think that this is linear sort and not bubble sort because here we are comparing one element to all the elements below it in the array and if a smaller element is found swapping them.
Accourding to me the correct code for bubble sort should be like
void bubble_sort_bottomsup(int a[], int n)
{
//implementing bubble sort
//a[] is the array to be sorted and n is the total number of elements in that array
for (int i = 1; i<n; i++)
{
for (int j = n-1; j>0; j--)
{
if (a[j] < a[j-1])
{
int temp;
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
}
is what I am saying correct?? I am new to c++ and this book a followed widely in my country so not so sure that there could really be a logical flaw in the book's code. And teachers at my school also keep on saying that the code given in the book for bubble sort is correct.
So please help me out.