Inserting a Card in a List of Sorted Cards in Python
Inserting a Card in a List of Sorted Cards
Problem Statement
Imagine that you are playing a card game. You are holding the cards in your hand and these cards are sorted. You are given exactly one new card. You have to put it into the correct place so that the cards you are holding are still sorted.
Algorithm
Step 1 : Start.
Step 2 : Read all numbers in an array A .
Step 3 : Read Key .
Step 4 : From first position to the end of the array compare key and array element .
Step 5 : If Key < A [ i ] then assign i to pos, and return pos .
Step 6 : From n-1 to pos move the elements one position down.
Step 7 : Now store key value in pos location .
Step 8 : Stop .
Flow Chart
Example
Consider the array from index 0 through index 5 is already sorted, and need to insert the key element 5 into this sorted sub-array, so that the sub-array from index 0 through index 6 is sorted .
![]() |
The slide operation just copies the element one position to the right. |
Pseudocode
void inserting_card ( int A [ ] , int n, int key)
{
int pos;
for ( i = 0 ; i < = n-1 ;i++)
{
if (key < A [ i ] )
{
pos = i;
return pos ;
break;
}
}
for ( i = n-1 ; i > = pos; i - - )
{
A [ i + 1 ] = A [ i ];
}
A [ pos ]=key;
}
Comments
Post a Comment