Bubble sorting

I've always wanted to know the concept behind the condition in the 2nd loop in all bubble sortings, even tho I never use it since I use the STL cont. sort function so the condition is always j < n - i - 1 , assuming the first loop is using variable i and n is the array size. I kinda know the -1 is cause we use index+1 inside the if condition so we dont wanna go out of the array boundaries but the use of n-i is what confuses me.

Thanks in advance!
Ive never done it with that condition, but I know it can be done. This is how I do it however -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>


void bubbleSort(int arr[], int size)
{
	for (int i = 0; i < size; i++)
	{
		for (int j = 0; j < size - 1; j++)
		{
			if (arr[j] > arr[j + 1])
			{
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}

int main()
{
	int arr[10] = { 10, 9, 2, 6, 1, 4, 5, 3, 8, 7 };

	bubbleSort(arr, 10);

	for (int i = 0; i < 10; i++)
	{
		std::cout << arr[i] << " ";
	}
	
	return 0;
}
@TarikNeaj

Yes that's the first way that came to my mind when I was asked to write a bubble sort the first time but then I looked up bubble sort and I found examples with this method and I honestly dunno why is this SPECIFIC condition used
Last edited on
If I understand it, its a case of arranging the deck chairs on the titanic. That is, its an efficiency tweak to a bad algorithm.
It keeps from checking items that are already sorted.
To see this, sort a very small list of like 5 numbers, and print the list after every iteration of the inner loop.

BTW the last time I checked, which was not long ago, the std::sort was not set up for multiprocessor. It may be now... its very fast, regardless.
Last edited on
Topic archived. No new replies allowed.