Download presentation
Presentation is loading. Please wait.
Published byMabel Warner Modified over 9 years ago
1
Dr. Sajib Datta CSE@UTA Feb 14, 2014
2
Ordering elements in some way For numeric data, ascending order is the most common Lots of techniques for sorting These techniques vary in performance both with runtime and usage of extra memory
3
Given a sequence of numbers, it compares adjacent numbers and swap them if necessary Repeats the above procedure until all numbers are in right place
4
4 10 9 6 -1 Pick 4, compare with 10
5
4 10 9 6 -1 Pick 10, compare with 9 Need to swap
6
4 9 10 6 -1
7
4 9 10 6 -1 Pick 10, compare with 6 Need to swap
8
4 9 6 10 -1
9
4 9 6 10 -1 Pick 10, compare with -1
10
4 9 6 -1 10 Notice, that 10 is at the right position Now, repeat from the beginning
11
4 9 6 -1 10 Compare 1 st element with 2 nd element
12
4 9 6 -1 10 Compare 2nd element with 3rd element Swap needed
13
4 6 9 -1 10
14
4 6 9 -1 10 Compare 3 rd element with 4 th element Swap needed
15
4 6 -1 9 10
16
4 6 -1 9 10 Now, do we need the compare 4 th with the 5 th ? We already know 5 th element is the largest. This implies, what we have as the 4 th element, it must be the second largest, and is already in the correct place.
17
4 6 -1 9 10 Now, repeat from the beginning again. But remember, we only need to go up to 3 rd this time.
18
1 st iteration places the largest number in the correct place 2 nd iteration places the second largest number in the correct place ….. …. i-th iteration places the i-th largest number in the correct place
19
#include #define ARR_SIZE 8 int main(void) { int intarr[ARR_SIZE] = {23, 4, 12, 8, 22, 1, 54, 9}, i, j, tmp; for(i = 0; i<ARR_SIZE-1; i++) { for(j = 0; j<ARR_SIZE-i-1; j++) { if(intarr[j]>intarr[j+1]) { tmp = intarr[j]; intarr[j] = intarr[j+1]; intarr[j+1] = tmp; } } } printf("The array sorted by Bubble Sort: "); for(i = 0; i< ARR_SIZE; i++) printf("%d ", intarr[i]); return 0; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.