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.
The first code block is not bubble-sort because bubble-sort swaps adjacent elements. "Linear sort" is a non-standard and confusing term, different people use this name for different things and I recommend against using it. There's no entry for "linear sort" in Wikipedia. The algorithm in the first block is commonly called selection sort.
Not directly related to your question: the book (and unfortunately the entire education system of at least one very large country) is using a horribly outdated dialect of C++. The language has changed very significantly since its advent ca 1983. As of now, the original dialect can only be found in very few very specialised niches. For learning modern C++, see StackOverflow's own The Definitive C++ Book Guide and List.