You are on page 1of 6

10

: ,
:
. .
: !

Insertion Sort
Insertion Sort )
(.
.
,
.
. , , )
( ,
. , ,
. 4 ,
)
( . ,
, ,.
.

) ( .
) ( ,
.
'
:InsertionSort
)]void insertionSort(char list[][SIZE

list
insertionSort
.
'
'
.
:
.
.1
.10
)\ .(n ,
.2
.
50.
2


.3
.define#
.
.4
) '_''*' ,'-', ,
( ,
, .strcmp
,insertionSort
.5
.
)( )(:
:
Please insert the strings:
We have here 10 strings.
They are not sorted.
But we intend to do so...
We wrote 4 strings
And this is the 5th
6th...
7th...
8th...
9th...
!10... We are done
:
The sorted strings:
!10... We are done
6th...
7th...
8th...
9th...
And this is the 5th
But we intend to do so...
They are not sorted.
We have here 10 strings.
We wrote 4 strings

#include <stdio.h>
#include <string.h>
#define SIZE 51
#define STR_NUM 10
void read_string(char str[])
/* This function is in charge of the user input of one string.
Assumption: Each string inserted is legit according to the assignment's preposition.
*/
{
int i=0;
char c;
scanf("%c",&c);
while ((c != '\n') && (i < SIZE-1))

{
str[i++]= c;
scanf("%c", &c);
}
str[i]='\0';
}
int find_index(char list[][SIZE], int index)
/* This function receives all the strings, and a maximal index as chosen by
"insertionSort".
It goes through the string array from the first string until the maximal index
In which the array has already been sorted, and returns the index where "list[index]"
belongs. */
{

int i=0;
for (i=0; i < index; i++)
if (strcmp(list[index], list[i]) <= 0)
return i;
return i;

void swap(char list[][SIZE], int start, int end)


/* This function receives all the strings, a starting index and an ending index.
"list[start] is where the current "list[end]" belongs (We wish to sort the strings),
so this function moves every other string forward,
and then switches the positions of "list[start]" and "list[end]",
effectively sorting the array up to and including the value in the "end" index. */
{

int i=0;
char temp[SIZE]= "";
strcpy(temp,list[end]);
for (i=end; i > start; i--)
strcpy(list[i], list[i-1]);
strcpy (list[start], temp);

}
void insertionSort(char list[][SIZE])
/* This function receives a pre-determined number of strings, and "sorts" them
according to
the assignment's requested algorithm, using the above "find_index" and "swap"
auxiliary functions . */
{
int i=0, j=0;
for (i=1; i < STR_NUM; i++)
swap(list, find_index(list, i), i);
}
int main()
//*************************************** Main Program
***************************************

{
int i=0;
char str[STR_NUM][SIZE];
printf("Please enter %d strings according to the assignment.\n\n", STR_NUM);
for (i=0; i < STR_NUM; i++)
{
printf("Please enter string number %d:\n", i+1);
read_string(str[i]);
printf("\n");
}
insertionSort(str);
printf("The following strings are after sorting:\n\n");
for (i=0; i < STR_NUM; i++)
printf("%s\n", str[i]);
printf("\n");
return 0;
}

You might also like