STRUCT – Definition And Access To Data

7.5. Simple Ordinations
It is very common to want to sort data that we have in an array. To achieve this, there are several simple algorithms, which are not particularly efficient, but are easy to program. The lack of efficiency refers to the fact that most of them are based on two loops ?? nested, so that in each pass a data is ordered, and there are as many passes as there are data, so that for an array with 1,000 data, you might have to make a million comparisons.


There are slight improvements (for example, changing one of the ?? for ?? a? While?, Not to review all the data if they were already partially ordered), as well as clearly more effective methods, but more difficult to program, some of which we will see later.


We will see three of these simple sorting methods, first looking at the appearance of the algorithm, and then putting the three together in an example that proves them:


Bubble method

(Exchange each consecutive pair that is not ordered)

For i = 1 to n-1
For j = i + 1 up to n
If A [i]> A [j]
Exchange (A [i], A [j])
(Note: some authors make the outer loop increasing and others decreasing, like this 🙂

For i = n descending to 1
For j = 2 up to i
If A [j-1]> A [j]
Swap (A [j-1], A [j])
Direct selection

(On each pass, look for the minor, and exchange it at the end of the pass)

For i = 1 to n-1
minor = i
For j = i + 1 up to n
If A [j] <A [minor]
minor = j
If minor <> i
Exchange (A [i], A [minor])
Direct insertion

(Compare each element with the previous ones -which are already ordered- and move it to its correct position).

For i = 2 to n
j = i-1
while (j> = 1) and (A [j]> A [j + 1])
Swap (A [j], A [j + 1])
j = j – 1
(It is improvable, not exchanging the data that moves with each element, but only at the end of each pass, but we will not go into more details).


Proposed exercises:

(7.5.1) A program that asks the user for 5 real numbers and displays them in order, using the bubble method.
(7.5.2) A program that creates an array of 7 integers and orders it with each of these three methods, showing the result of the intermediate steps.
Write a C program to separate even and odd numbers of an array and put them in two separate arrays.
Afflluence Writing Service

You may also like...

1 Response

  1. 2017

    […] Previous story STRUCT – Definition And Access To Data […]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

error: Content is protected !!