14 - 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

14 - ICS 103 Computer Programming in C Handout-14 Topic 1-D...

This preview shows page 1 - 3 out of 7 pages.

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
Image of page 1
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
Image of page 2
Image of page 3

You've reached the end of your free preview.

Want to read all 7 pages?

  • Spring '10
  • zaman
  • #include, #define, Search algorithm

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

Stuck? We have tutors online 24/7 who can help you get unstuck.
A+ icon
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes