Indirect Sorting
Indirect Sorting
1
Criteria for Evaluating Sorts
Sorting algorithms can be compared based on several factors.
2
QUICKSORT
• Most well-known (good) sorting algorithms are recursive.
They follow the following general strategy:
3
QUICKSORT
• As the name implies quicksort is the fastest known
sorting algorithm in practice.
4
QUICKSORT: Implementation I
/* Return median of Left, Center, and Right */
/* Order these and hide the pivot */
Qsort( A, Left, i - 1 );
Qsort( A, i + 1, Right );
}
else /* Do an insertion sort on the subarray */
InsertionSort( A + Left, Right - Left + 1 );
}
6
INDIRECT SORTING
• Sometimes, we need to sort large structures or objects by a
certain key.
– payroll records, with each record consisting of a name, address, phone
number, financial information such as salary, and tax information.
– sort this information by one particular field, such as the name or
employee number.
7
INDIRECT SORTING
8
INDIRECT SORTING
1. Create an array of pointers (p)
9
Pointer Class definition for Indirect Sorting
11
We can write
int *P[size];
int ** P= new int * [size];
12
Array a 200 100 400 500 300
Addresses A[0]=1000 A[1]=1001 A[2]=1002 A[3]=1003 A[4]=1004
of a
P[0]=1001 P[0]=1000 P[0]=1004 P[0]=1002 P[0]=1003
Sorted p[ ]
13
Array a
14
Pointer Array p [ ] 100 200 300 400 500
P[0]=1001 P[0]=1000 P[0]=1004 P[0]=1002 P[0]=1003
Sorted p[ ] based
on values P[0]=1000 P[0]=1001 P[0]=1002 P[0]=1003 P[0]=1004
we have to
change manually
15
Initial iteration when i=0
Nextj= 1001-1000 1
A[0]= 100
P[0]= &a[0] 1000
J=1
A[1]= 200
P[1] = &a[j] 1001
i=0, j=0,
tmp=200
16
Nextj= 1001-1000 1
A[0]= 100
P[0]= &a[0] 1000
J=1
A[1]= 200
P[1] = &a[j] 1001
i=0, J=1
tmp=200
17
Initial iteration when i=1
i=0, i=1 , j= i
Tmp=200
18
Initial iteration when i=2
i=0, i=2 , j= i
Tmp=400
19
Initial iteration when i=2
i=0, i=2 ,
Tmp=400 J=4
20
Initial iteration when i=2
J=4
P[4] != &a[2] which is true
Nextj= p[4]- &a[0] 1003 -1000 =3
A[4]= * p[4] 500
P[4] = &a[4] 1004
J=3
P[3] != &a[2] which is false
A[3]= tmp 400
P[3] = &a[3] 1003
J=3
P[3] != &a[2] which is false
A[3]= tmp 400
P[3] = &a[3] 1003
J=3
P[3] != &a[2] which is false
A[3]= tmp 400
P[3] = &a[3] 1003
i=4 , i=4,
tmp=500
24
Initial iteration when i=2
J=3
P[3] != &a[2] which is false
A[3]= tmp 400
P[3] = &a[3] 1003
SORTED ARRAY
25