c++ vector bubble sort

Write your question here.
I have written bubble sort function for a vector passed in by reference in two different ways, but they do not work. What is wrong with them?

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
void bubbleSort(std::vector<int> & vector2){

	bool sortDone = 0;
	while (sortDone == 0) {
		for (int i = 0; i < vector2.size() - 1; i++) {
			sortDone = 1;
			if (vector2[i + 1] <= vector2[i]) {
				int j = vector2[i + 1];
				int k = vector2[i];
				vector2[i] = j;
				vector2[i + 1] = k;
				sortDone = 0;
			}
		}
	}

}

void bubbleSort(std::vector<int> & vector2){

	for (int i = 0; i < vector2.size() - 1; i++) {
		for (int t = 0; t < vector2.size() - i - 1; t++) {
			if (vector2[i + 1] <= vector2[i]) {
				int j = vector2[i + 1];
				vector2[i + 1] = vector2[i];
				vector2[i] = j;
			}
		}
	}

}
  Put the code you need help with here.
In the top function the vector will stop sorting prematurely if the last 2 entries of the vector are already sorted properly (lower left, higher right)

Why are you comparing <= instead of just <? Identical values really don't need to be swapped.
The first one is almost right, it will work if you change:

1
2
3
	while (sortDone == 0) {
		for (int i = 0; i < vector2.size() - 1; i++) {
			sortDone = 1;


to

1
2
3
4
	while (sortDone == 0) {
               sortDone = 1;
		for (int i = 0; i < vector2.size() - 1; i++) {
			


You only should set done once, not every time you check elements. If they swap even once then you need to iterate again. And yes don't check = too, it will cause infinite loops when elements are not unique.
Last edited on
Topic archived. No new replies allowed.