Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS148 Introduction to Programming II

Similar presentations


Presentation on theme: "CS148 Introduction to Programming II"— Presentation transcript:

1 CS148 Introduction to Programming II
Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture 7:2/7/2003 Lecture 7: 2/7/2003 CS148 Spring 2003

2 Outline Sorting techniques Bubble Sort Selection Sort
Lecture 7: 2/7/2003 CS148 Spring 2003

3 Bubble Sort Each iteration, move the next largest item into correct position. Compare each pair of Consecutive elements moving largest element up void BubbleSort(int narray[],int length) { for (int i = 1; i < length; i++) //bubble up max{narray[0..n-i]} for (int j = 0; j < length-i ; j++) if (narray[j] > narray[j+1]) SwapArrayElements (narray[j], narray[j+1]); } Lecture 7: 2/7/2003 CS148 Spring 2003

4 Selection Sort 1/2 (length-1) iterations where length is the array size Each iteration selecting the largest element narray[j] and swapping it with the element that is in the position where narray[j] should be 1st iteration: select largest of all elements and swap with narray[length-1] 2nd iteration: select largest of remaining unsorted elements narray[0 .. length-2] and swap with narray[length-2] .. Lecture 7: 2/7/2003 CS148 Spring 2003

5 Selection Sort 2/2 void SelectionSort(int narray[],int length) {
for (int i = 1 ; i < length ; i++) //select narray[k] = max { narray[0], narray[1], ..., narray[n-i] int k = 0; for (int j = 1; j <= length-i; j++) if (narray[j] > narray[k]) k =j; SwapArrayElements(narray[k], narray[length-i]); } Lecture 7: 2/7/2003 CS148 Spring 2003


Download ppt "CS148 Introduction to Programming II"

Similar presentations


Ads by Google