What is Sorting ?
is the process of placing elements from a collection in some kind
refers to ordering data in an increasing or decreasing fashion
according to some linear relationship among the data items.
can be done on names, numbers and records. For example, it is
relatively easy to look up the phone number of a friend from a
telephone dictionary because the names in the phone book have
been sorted into alphabetical order.
Types of Sorting
In this method, sorting is done by inserting elements into
an existing sorted list. Initially, the sorted list has only one
element. Other elements are gradually added into the list
in the proper position.
In this technique, the first element is selected and
compared with all other elements. If any other element is
less than the first element swapping should take place. By
the end of this comparison, the least element most top
position in the array.
This is known as pass1. In pass II, the second element is
selected and compared with all other elements. Swapping
takes place if any other element is less than selected element.
This process continuous until array is sorted.
9 2 5 7 4 8 on pass 1 look for smallest in 1st to 6th swap 2nd
with first giving
2 9 5 7 4 8 on pass 2 look for smallest in 2nd to 6th swap 5th
with second giving
2 4 5 7 9 8 on pass 3 look for smallest in 3rd to 6th swap 3rd
with third giving
2 4 5 7 9 8 on pass 4 look for smallest in 4th to 6th swap 4th
with fourth giving
2 4 5 7 9 8 on pass 5 look for smallest in 5th to 6th swap 5th
with 6th giving
2 4 5 7 8 9 sorted.
The exchange sort is almost similar as the bubble sort. In fact
some people refer to the exchange sort as just a different bubble
sort. The exchange sort compares each element of an array and
swap those elements that are not in their proper position, just like
a bubble sort does. The only difference between the two sorting
algorithms is the manner in which they compare the elements.
The exchange sort compares the first element with each element
of the array, making a swap where is necessary.
1. Compare the first pair of numbers (positions 0 and 1) and
reverse them if they are not in the correct order.
2. Repeat for the next pair (positions 1 and 2).
3. Continue the process until all pairs have been checked.
4. Repeat steps 1 through 3 for positions 0 through n - 1 to i
(for i = 1, 2, 3, ...) until no pairs remain to be checked.
5. The list is now sorted.
is an efficient algorithm for sorting a small number of
elements. Insertion sort works the same way as one would sort
a bridge or gin rummy hand, i.e. starting with an empty left
hand and the cards face down on the table. One card at a time
is then removed from the table and inserted into the correct
position in the left hand. To find the correct position for a card,
it is compared with each of the cards already in the hand,
from right to left.
To insert 12, we need to
make room for it by
moving first 36 and then