8 December

Insertion into an ordered array

#include <stdio.h>
const int MAX = 8;

void print_list(int list[MAX], int count)
{
printf("%d items: ", count);
for(int i = 0 ; i < count; i++)
{
printf("%3d ", list[i]);
}
printf("\n");
}

void insert_in_order(int list[MAX],
int& count,
int new_element)
{
// Phase 0: Check capacity of array
if(count >= MAX) {
printf("Error: array at capacity.\n");
return;
}
// Phase 1: find where to insert
int i = 0;
while( i < count && new_element > list[i] )
{
i++;
}
//printf("I choose to insert at %d\n", i);
// Phase 2: shift elements to the right
for(int j = count; j > i ; j--)
{
list[j] = list[j-1];
}
list[i] = new_element;
count++;
}

int main()
{
int count = 0;
int list[MAX];
print_list(list, count);
int num;
printf("Enter number: ");
scanf("%d", &num);
while(num != -1) {
insert_in_order(list, count, num);
print_list(list, count);
printf("Enter number: ");
scanf("%d", &num);
}
return 0;
}

Example with strings as arrays

#include <stdio.h>
int main()
{
char s[] = "Hello.";
printf("Your string: %sn", s);
s[1] = 'a';
printf("Your string: %sn", s);
s[4] = '0';
printf("Your string: %sn", s);
return 0;
}

©2011 Christopher League · some rights reserved · CC by-sa