What is Bubble Sort or Bubble Sorting?
•Sorting data
•Bubble sort (sinking sort)
•Example:
•Swapping variables
•Solution
Bubble Sorting in C++:
In Bubble Sort, we follow following steps:
•Sorting data
–Important computing application
–Virtually every organization must sort some data
•Massive amounts must be sorted
•Bubble sort (sinking sort)
–Several passes through the array
–Successive pairs of elements are compared
•If increasing order (or identical), no change
•If decreasing order, elements exchanged
–Repeat these steps for every element
•Example:
–Go left to right, and exchange elements as necessary
•One pass for each element
–Original: 3 4 2 7 6
–Pass 1: 3 2 4 6 7 (elements exchanged)
–Pass 2: 2 3 4 6 7
–Pass 3: 2 3 4 6 7 (no changes needed)
–Pass 4: 2 3 4 6 7
–
–Small elements "bubble" to the top (like 2 in this example)
•Swapping variables
int x = 3, y = 4;
y = x;
x = y;
•What happened?
–Both x and y are 3!
–Need a temporary variable
•Solution
int x = 3, y = 4, temp = 0;
temp = x; // temp gets 3
x = y; // x gets 4
y = temp; // y gets 3
Bubble Sorting in C++:
#include<iostream>
using namespace std;