Java Reference
In-Depth Information
{
int tmp=array[i];
array[i]=array[j];
array[j]=tmp;
}
Sorting is an entire area field of computer science in itself with many algorithms
and remaining challenges to tackle. Next, we present two flagship algorithms:
The selection sort and quicksort.
6.4.1 Sorting by selection:
SelectionSort
The selection sort is very natural and proceeds as follows:
-
First, seek for the smallest element of the array: This is the SELECTION
stage.
-
Then, reiterate the minimum selection for the remaining sub-array:
array[1], ..., array[n-1]
That is, at stage i+1, the selection sort seeks for the smallest elements for the
sub-array
array[j], array[j+1], ..., array[n-1]
To program the selection sort, we use two nested loops:
-
The inner loop selects and puts the smallest element in front of the current
array,
-
The outer loop repeats the minimum selection/swap for all subarrays.
These steps are summarized in the source code below:
Program 6.6
Sorting by selecting iteratively the minimum elements
static void
swap (
int
[ ] array ,
int
i,
int
j)
{
int
tmp=array [ i ]; array [ i]=array [ j ]; array [ j]=tmp;
}
static void
SelectionSort(
int
[]
array)
int
n=array . length ;
for
(
int
i=0;i
<
n
−
1; i ++)
{
for
(
int
j=i +1;j
<
n ; j ++)
{
if
(GreaterThan(array [ i ] , array [ j ]) )
swap(array , i , j ) ;
}
}
}
Search WWH ::
Custom Search