Lec 7
Lec 7
Lecture (7)
Array
(Cont.)
Introduction To Sorting
• Sorting means arranging the elements of an array so that they are placed in
some relevant order which may be either ascending or descending.
• If A is an array, then the elements of A are arranged in an ascending order in
such a way that A[0] < A[1] < A[2] < ...... < A[N].
• For example, if we have an array that is declared and initialized as:
• After the end of the first pass, the largest element is placed at the highest
index of the array. All the other elements are still unsorted
Bubble Sort
• After the end of the second pass, the second largest element is placed at the
second highest index of the array. All the other elements are still unsorted.
Bubble Sort
• After the end of the third pass, the third largest element is placed at the third
highest index of the array. All the other elements are still unsorted.
Bubble Sort
• After the end of the fourth pass, the fourth largest element is placed at the
fourth highest index of the array. All the other elements are still unsorted.
Bubble Sort
• After the end of the fifth pass, the fifth largest element is placed at the fifth
highest index of the array. All the other elements are still unsorted.
Bubble Sort
• After the end of the sixth pass, the sixth largest element is placed at the sixth
largest index of the array. All the other elements are still unsorted.
• The algorithm for Selection • During the Ith pass, we need to find the position POS
Sort of array A having total of the smallest elements from A[I], A[I+1], ..., A[N-1].
number of elements N is:
• To find the smallest element, we use a variable
SMALL to hold the smallest value in the sub-array
ranging from A[I] to A[N-1]. Then, swap A[I] with
A[POS].
Example
• Write a program to enter n
numbers in an array.
Redisplay the array with
elements being sorted in
ascending order using
selection sort?
Thank You !