Translate

Saturday, 2 August 2014

Array Algorithms

An array that uses a single subscript is called a one dimensional array. This is because one index is used to access the values in the array. Its cells are like numbered boxes lined up one after the other in a line.


It is annoying to count the elements in an array. Worse, when you write a program you may not know in advance how many elements are needed. Array objects can be created as the program runs. Some languages allow the dynamic allocation of memory for Array at program run-time.

In simple examples, the differences between array algorithms and non-array algorithms are subtle. For example, consider the algorithm which finds the missing number in a series of 100 numbers.

#include <stdio.h>

#define SIZE 100 // this should be a 100 numbers

void a_sort(int[],int,int);
int missing_number(int[], int);

int main(){
    int m, i,n, array_numbers[SIZE];
 
    puts("A hundred numbers");
    for(i=0; i<SIZE; i++){
        printf("Enter a number: ");
        scanf("%d",&n);
        array_numbers[i]=n;
    }
 
    a_sort(array_numbers, 0,SIZE);
 
    m = missing_number(array_numbers, SIZE);
 
    printf("Missing number is: %d\n", m);
 
    system("pause");
}

void a_sort(int arrayNum[], int i, int len){
      int temp;
   
      if(i<len){
         len--;
       
         if(arrayNum[i] > arrayNum[len]){
               temp = arrayNum[i];
               arrayNum[i] = arrayNum[len];
               arrayNum[len] = temp;
         }
         i++;
       
         a_sort(arrayNum, i, len);
      }
}

int missing_number(int arrayNum[], int len){
     int i,m;
   
     for(i=0; i<len; i++){
              if(arrayNum[i]!=i) return i;
     }
     return -1;
}


The C program allows the input of 100 numbers. The numbers are stored in an array variable arrayNum[]. The program allows the numbers to be inputed in any order. A simple sort is done on the array using the function a_sort(int arrayNum[], int i, int len) which takes the arrray of numbers, the last index of the array, and the length of the array. The function orders the numbers from lowest to highest. The missing number is found using the missing_number(int arrayNum[], int len) which takes the array of numbers, and the length of the array. The function finds the missing number of the from 0 to 99.

The possible output for the program is:

A hundred numbers

Enter a number: 5

Enter a number: 3

Enter a number: 2

Enter a number: 1

Enter a number: 4

.......


Enter a number: 100

Missing number is: 12

Press any key to continue . . .


No comments:

Post a Comment