Exchange Sort
index Comparing Elements
N numbers
1 97 82 76 29 17 (1,2) (1,3) (1,4) (1,5)
2 82 97 97 97 97 J <- 2 to 5
3 76 76 82 82 82 Pass-1 J <- 1+1 to 5 J <- 1+1 to N
4 29 29 29 76 76 ( 1, j)
5 17 17 17 17 29
1 17 17 17 17 (2,3) (2,4) (2,5)
2 97 82 76 29 J <- 3 to 5
3 82 97 97 97 Pass-2 J <- 2+1 to 5 J <- 2+1 to N
4 76 76 82 82 ( 2, j)
5 29 29 29 76
1 17 17 17 (3,4) (3,5)
2 29 29 29 J <- 4 to 5
3 97 82 76 Pass-3 J <- 3+1 to 5 J <- 3+1 to N
4 82 97 97 ( 3, j)
5 76 76 82
1 17 17 (4,5)
2 29 29 J <- 5 to 5
3 76 76 Pass-4 J <- 4+1 to 5 J <- 4+1 to N
4 97 82 ( 4, j)
5 82 97
Pass-i J <- i+1 to N
No. of No. of
Numbers Passes
5 4
N N-1
i <- 1 to N-1
j <- i+1 to N
If A[i] > A[j) then
Interchange A[i] and A[j]
Exchange Sort
Problem: Arrange a set of N numbers in ascending order
Input : Value of N, N numbers { ie. An array A[1..N] of N elements}
Output : Sorted list of numbers in A[1..N]
Pseudo Code
Start
Input N
For i = 1 to N Step 1 // Reading numbers into array
Input A[ i ]
EndFor
For i = 1 to N-1 Step 1
For j = i+1 to N Step 1
If A[i] > A[j] Then
Let temp = A[i] // Interchange
Let A[i] = A[j]
Let A[j] = temp
Endif
EndFor // End of inner loop
EndFor
For i = 1 to N step 1 // Output Sorted numbers
Print A[ i ]
EndFor
Stop