14 - ICS 103: Computer Programming in C Handout-14 Topic:...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
ICS 103: Computer Programming in C Handout-14 Topic: 1-D Array ( Sorting & Searching in 1-D Array). Objective: Teach the Selection Sort , Linear search & Binary Search algorithms for 1-D Array. What is Sorting? Sorting is the re-arrangement of a collection of data according to some key-field. We shall consider Selection Sort of sorting methods in this Lecture. Selection Sort Algorithm: This includes the following steps: 1. Find the smallest (or largest) item in the list. 2. Place this item at the beginning of the list. 3. Repeat steps 1 and 2 starting at the beginning of the remaining list ( i. e for the other passes). Notes: 1. Selection Sort has the advantage of simplicity and is adequate for small list of few hundred records. 2. The problem with selection sort is that the main loop executes n (number of records) times. More over, in each iteration it has to search the rest of the records for a minimum – about n comparisons. Thus it needs approximately n*n steps. For this reason, it is sometimes called a quadratic sorting method. 3. Another problem with selection sort is that it always scans the whole list looking for smallest even if the data happen to be in order. Algorithm for Selection Sort: #include<stdio.h> void selection_sort (int x[], int size) { int k,pass,minpos,temp; for (k=0;k<size-1; k++) { Page 1 of 7
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
minpos=k; for(pass=k+1; pass<=size-1; pass++) { if(x[pass]<x[minpos]) minpos=pass; } temp=x[minpos]; x[minpos]=x[k]; x[k]=temp; } } // End of function int main() { int y[]={4,2,9,1,5}; int k , size=5; selection_sort (y, size); // Function call printf("The sorted array is :\n"); for(k=0; k<size; k++) printf("%d\n",y[k]);
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 05/09/2010 for the course ICS 102 taught by Professor Zaman during the Spring '10 term at Abilene Christian University.

Page1 / 7

14 - ICS 103: Computer Programming in C Handout-14 Topic:...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online