Sorting
What is Sorting?
1. Arranging elements in a list in ascending or descending order
2. List = Array
7 12 4 18 1 9 3 6 13 2arr unsorted
arr 1 2 3 4 6 7 9 12 13 18 sorted (ascending)
18 13 12 9 7 6 4 3 2 1arr sorted (descending)
6 2 2 1 7 1 5
1 1 2 2 5 6 7
7 6 5 2 2 1 1
arr
arr
arr
unsorted
non-decreasing
non-increasing
Bubble Sort
Logic : Works by repeatedly swapping adjacent elements if they are out of order
Example : (5 4 3 2 1)
Pass 1 : (5 4 3 2 1) ----> (4 5 3 2 1)
(4 5 3 2 1) ----> (4 3 5 2 1)
(4 3 5 2 1) ----> (4 3 2 5 1)
(4 3 2 5 1) ----> (4 3 2 1 5)
Pass 2 : (4 3 2 1 5) ----> (3 4 2 1 5)
(3 4 2 1 5) ----> (3 2 4 1 5)
(3 2 4 1 5) ----> (3 2 1 4 5)
Pass 3 : (3 2 1 4 5) ----> (2 3 1 4 5)
(2 3 1 4 5) ----> (2 1 3 4 5)
Pass 4 : (2 1 3 4 5) ----> (1 2 3 4 5)
Sorted Array : (1 2 3 4 5)
Selection Sort
Logic : Works by repeatedly finding the minimum element and putting it at the beginning
Example : (5 4 3 2 1)
Pass 1 : (5 4 3 2 1) ----> Finding minimum element to be 1 and putting it at beginning
(1 4 3 2 5)
Pass 2 : (1 4 3 2 5) ----> Finding minimum element to be 2 and putting it at beginning
(1 2 3 4 5)
Pass 3 : (1 2 3 4 5) ----> Finding minimum element to be 3 and putting it at beginning
(1 2 3 4 5)
Pass 4 : (1 2 3 4 5) ----> Finding minimum element to be 4 and putting it at beginning
(1 2 3 4 5)
Sorted Array : (1 2 3 4 5)

Sorting

  • 1.
  • 2.
    What is Sorting? 1.Arranging elements in a list in ascending or descending order 2. List = Array 7 12 4 18 1 9 3 6 13 2arr unsorted arr 1 2 3 4 6 7 9 12 13 18 sorted (ascending) 18 13 12 9 7 6 4 3 2 1arr sorted (descending)
  • 3.
    6 2 21 7 1 5 1 1 2 2 5 6 7 7 6 5 2 2 1 1 arr arr arr unsorted non-decreasing non-increasing
  • 4.
    Bubble Sort Logic :Works by repeatedly swapping adjacent elements if they are out of order Example : (5 4 3 2 1) Pass 1 : (5 4 3 2 1) ----> (4 5 3 2 1) (4 5 3 2 1) ----> (4 3 5 2 1) (4 3 5 2 1) ----> (4 3 2 5 1) (4 3 2 5 1) ----> (4 3 2 1 5) Pass 2 : (4 3 2 1 5) ----> (3 4 2 1 5) (3 4 2 1 5) ----> (3 2 4 1 5) (3 2 4 1 5) ----> (3 2 1 4 5) Pass 3 : (3 2 1 4 5) ----> (2 3 1 4 5) (2 3 1 4 5) ----> (2 1 3 4 5) Pass 4 : (2 1 3 4 5) ----> (1 2 3 4 5) Sorted Array : (1 2 3 4 5)
  • 5.
    Selection Sort Logic :Works by repeatedly finding the minimum element and putting it at the beginning Example : (5 4 3 2 1) Pass 1 : (5 4 3 2 1) ----> Finding minimum element to be 1 and putting it at beginning (1 4 3 2 5) Pass 2 : (1 4 3 2 5) ----> Finding minimum element to be 2 and putting it at beginning (1 2 3 4 5) Pass 3 : (1 2 3 4 5) ----> Finding minimum element to be 3 and putting it at beginning (1 2 3 4 5) Pass 4 : (1 2 3 4 5) ----> Finding minimum element to be 4 and putting it at beginning (1 2 3 4 5) Sorted Array : (1 2 3 4 5)