ICS 103: Computer Programming in C
Handout14
Topic:
1D Array (
Sorting & Searching in 1D
Array).
Objective:
•
Teach the
Selection Sort
,
Linear search
&
Binary Search
algorithms for 1D Array.
What is Sorting?
•
Sorting is the rearrangement of a collection of data according to
some keyfield.
•
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<size1; k++)
{
Page 1 of 7
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Documentminpos=k;
for(pass=k+1; pass<=size1; 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]);
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '10
 zaman
 #include, #define, Search algorithm

Click to edit the document details