Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Sudeshna Sarkar
7th Feb 2017
Searching an Array:
Linear and Binary Search
no yes
0 n-1
<=key >key
L R L R
Look at [(L+R)/2]. Move L or R to the middle
depending on test.
Repeat search operation in the reduced interval.
Spring 2012 Programming and Data Structure 9
Contd.
/* If key appears in x[0..size-1], return its location, pos s.t. x[pos]==key.
If not found, return -1 */
-17 -5 3 6 12 21 45 63 50
x: 3 12 -5 6 72 21 -7 45
Swap
x: -7 -5 3 6 12 21 72 45
x: -7 12 -5 6 72 21 3 45
Swap x: -7 -5 3 6 12 21 72 45
x: -7 -5 12 6 72 21 3 45
x: -7 -5 3 6 12 21 45 72
x: -7 -5 3 6 72 21 12 45
x: -7 -5 3 6 72 21 12 45
Selection Sort
General situation :
0 k size-1
x: smallest elements, sorted remainder, unsorted
Steps :
Find smallest element, mval, in x[k..size-1]
Swap smallest element with x[k],
Increase k.
0 k mval size
x: smallest elements, sorted
swap
Subproblem: Find smallest element
/* Yield location of smallest element in x[k .. size-1];*/
int min_loc (int x[ ], int k, int size)
int j, pos; /* x[pos] is the smallest element found so far */
pos = k;
for (j=k+1; j<size; j++)
if (x[i] < x[pos])
pos = j;
return pos;
}
Selection Sort
/* Sort x[0..size-1] in non-decreasing int min_loc (int x[ ], int k, int size)
order */ int j, pos;
pos = k;
for (j=k+1; j<size; j++)
int selsort (int x[ ], int size) { if (x[i] < x[pos])
int k, m; pos = j;
for (k=0; k<size-1; k++) { return pos;
m = min_loc (x, k, size); }
temp = a[k];
a[k] = a[m];
a[m] = temp;
}
}
Example
Swap for (k=0; k<size-1; k++) {
k pos
pos = k;
x: 3 12 -5 6 72 21 -7 45 for (j=k+1; j<size; j++) {
if (x[j] < x[pos])
Swap pos = j;
k pos
}
x: -7 12 -5 6 72 21 3 45 temp = x[k];
x[k] = x[pos];
Swap x[pos] = temp;
}
x: -7 -5 12 6 72 21 3 45
x: -7 -5 3 6 12 21 72 45
x: -7 -5 3 6 72 21 12 45
x: -7 -5 3 6 12 21 72 45
x: -7 -5 3 6 72 21 12 45
x: -7 -5 3 6 12 21 45 72
Analysis
How many steps are needed to sort n things ?
Total number of steps proportional to n2
No. of comparisons?
(n-1)+(n-2)++1= n(n-1)/2
Of the order of n2
i Compare and
Shift till x[i] is
larger.
j size-1
0
o Best Case?