GDC Class Notes

Class Notes of Graduate Diploma in Computing in Unitec

Data Structure

Basic Coding

  • define an array
  • populate it
  • Search - brute force
  • sorting (beofore search)
  • Binary Search

Code Example (C)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <stdio.h>
#include <stdlib.h> //
#include <time.h> //for random seed
// #include <stdbool.h> //c99 for boolean

// like #include "stdafx.h" use " " toinclude from same directory
// in c, if there is only one statement, {} is not necessary

int main(){
printf("Set seeding\n");
int seed = time(NULL);
srand(seed);

int A[100];

// populate the array
for (int i = 0; i<100; i++){
A[i] =rand()%1000;
printf("A[%d]: %d \n", i, A[i]);
}

// A[99]=300; // cheating for finding

// bubble sort
int temp =0;
for (int i=0; i<99;i++){
for (int j=i+1; j<100;j++){
if (A[i]>A[j]){
temp = A[i];
A[i]=A[j];
A[j]= temp;
}
}
}

// re print sorted array
for (int i = 0; i<100; i++)
printf("A[%d]: %d \n", i, A[i]);

// searching
int ntf =300;


// brute forceing searching
int position=-1;
for (int i=0; i<100; i++){
if (ntf==A[i]){
ntf =A[i];
break;
}
}

if (position !=-1) {
printf("Found by brute ntf %d at %i", ntf, position );
}else {
printf("Cannot found %d \n", ntf);
}

// binary search

int start=0;
int end = 99;
int found = start+(end-start)/2;

while (A[found] != ntf){

if (A[found] > ntf ){
end = found;
}else {
start = found;
}

found = start+(end-start)/2;
if (found == start || found == end){
found = -1;
break;
}
}

if (found ==-1){
printf("Cannot found %d \n", ntf);
}else{
printf("Found throught binary searching %d\n", found );
}

// system("pause"); // for pause console to show result
// getchar(); // to receive input from console
return 0;
}

More Workds

  • find 2 other sorting methods
  • 1 searching method