-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubbleSort.cpp
More file actions
60 lines (50 loc) · 1.66 KB
/
bubbleSort.cpp
File metadata and controls
60 lines (50 loc) · 1.66 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Created by Frank M. Carrano and Tim Henry.
// Copyright (c) 2013 __Pearson Education__. All rights reserved.
// Listing 11-2.
#include <iostream>
#include <string>
using namespace std;
template<class ItemType>
/** Sorts the items in an array into ascending order.
@pre None.
@post theArray is sorted into ascending order; n is unchanged.
@param theArray The given array.
@param n The size of theArray. */
void bubbleSort(ItemType* theArray, unsigned int n)
{
bool sorted = false; // False when swaps occur
int pass = 1;
while (!sorted && (pass < n))
{
// At this point, theArray[n+1-pass..n-1] is sorted
// and all of its entries are > the entries in theArray[0..n-pass]
sorted = true; // Assume sorted
for (int index = 0; index < n - pass; index++)
{
// At this point, all entries in theArray[0..index-1]
// are <= theArray[index]
int nextIndex = index + 1;
if (theArray[index] > theArray[nextIndex])
{
// Exchange entries
std::swap(theArray[index], theArray[nextIndex]);
sorted = false; // Signal exchange
} // end if
} // end for
// Assertion: theArray[0..n-pass-1] < theArray[n-pass]
cout << "Pass " << pass - 1 << " gives: " << endl;
for (int i = 0; i < n; i++)
cout << theArray[i] << " ";
cout << endl;
pass++;
} // end while
} // end bubbleSort
int main()
{
string a[11] = {"6", "3", "9", "8", "8", "3", "1", "7", "3", "9", "1"};
bubbleSort(a, 11);
cout << "After sorting " << endl;
for (int i = 0; i < 11; i++)
cout << a[i] << " ";
cout << endl;
} // end main