- We must assume the items are not ordered.
- Algorithm 1:
FindItemK(A, n, k)
- sort(A,0,n-1)
- return A[k-1]
- This assumes that the sort sorts items 0-n and places the smallest item at position 0.
- In some sense this relates finding the kth smallest item to sorting.
- And the performance of the algorithm depends on the performance of sorting.
- Let us experiment a bit.
- We need to know about random numbers, srand, rand
- We need to know about times
- This is a system call that returns information about process time
- It is returned in a time structure
struct tms {
clock_t tms_utime; /* user time */
clock_t tms_stime; /* system time */
clock_t tms_cutime; /* user time of children */
clock_t tms_cstime; /* system time of children */
};
- We need to include <sys/times.h>
- Each call will return time used so far in each area
-
times(&start);
perform task
times(&end);
- The code
- We should probably investigate two things:
- What happens when n changes?
- What happens when k changes?
- I ran the program on cslab177
-
-
- Algorithm 2:
FindItemK(A, n, k)
- sort(A,0,k-1);
- for i<- k to n-1 do
- if (A[k-1] > A[i] do
- place(ary, k, ary[i])
- return A[k-1]
- place is a routine that will insert an item into an
an array at it's proper position.
place(A, n, item)
- position <- n-1
- while position > 0 and A[position-1] > item do
- A[position] <- A[position-1]
- A[position] <- item