Posts

Showing posts from September, 2015

Bubble Sort

Bubble Sort Introduction: 1) Compares each element in an array with its adjacent element. 2) If the one on the right hand side is greater(or lesser based on the order of sort required) the elements are swapped. 3) This iteration is performed multiple times untill, there is one iteration which makes no swaps Process: Consider:[3,4,1,2] should be sorted in ascending order Iteration 1: Input: [3,4,1,2] Step 1: compare 3 and 4. 3 <4 => no change => [3,4,1,2] Step 2: Compare 4 and 1. 4 > 1 => swap => [3,1,4,2] Step 3: Compare 4 and 2. 4 > 2 => swap => [3,1,2,4] Result: [3,1,2,4] => Greatest element has moved to its position(the end) swapped = true Iteration 2: Input: [3,1,2,4] Step 1: compare 3 and 1. 3 > 1 => swap => [1,3,2,4] Step 2: Compare 3 and 2. 3 > 2 => swap => [1,2,3,4] Result: [1,2,3,4] =>