You are on page 1of 27

A data structure is a particular way of storing and organizing data in a computer so that it

can be used efficiently

Different kinds of data structures are suited to different kinds of applications, and some are
highly specialized to specific tasks. For example, B-trees are particularly well-suited for
implementation of databases, while compiler implementations usually use hash tables.

Data structures are used in almost every program or software system. Data structures provide
a means to manage huge amounts of data efficiently, such as large databases. Usually,
efficient data structures are a key to designing efficient algorithms. Some formal design
methods and programming languages emphasize data structures, rather than algorithms, as
the key organizing factor in software design.

Data structures are generally based on the ability of a computer to fetch and store data at any
place in its memory, specified by an address a bit string that can be itself stored in memory
and manipulated by the program. Thus the struct and array data structures are based on
computing the addresses of data items with arithmetic operations; while the linked data
structures are based on storing addresses of data items within the structure itself.

The implementation of a data structure usually requires writing a set of procedures that create
and manipulate instances of that structure. The efficiency of a data structure cannot be
analyzed separately from those operations. This observation motivates the theoretical concept
of an abstract data type, a data structure that is defined indirectly by the operations that may
be performed on it.

Common data structures include: array, linked list, hash-table, heap, Tree (Binary Tree, Btree, red-black tree, trie), stack, and queue.

Topics that will be covered in this section include:

Array-Based Implementations

Recall that
o an array is a named collection of homogeneous items
o An items place within the collection is called an index

If there is no ordering on the items in the container, we call the container unsorted

If there is an ordering, we call the container sorted

Linked Implementation

An implementation based on the concept of a node

A node is made up of two pieces of information


o the item that the user wants in the list, and
o a pointer to the next node in the list

Lists

List operations
o Create itself
o Insert an item
o Delete an item

o Print itself
o Know the number of items it contains

Sorting

Because sorting a large number of elements can be extremely time-consuming, a good


sorting algorithm is very desirable

We present several quite different sorting algorithms

Selection Sort

List of names
o Put them in alphabetical order

Find the name that comes first in the alphabet,


and write it on a second sheet of paper

Cross out the name on the original list

Continue this cycle until all the names on the original list have been
crossed out and written
onto the second list, at which point the second list is sorted

A slight adjustment to this manual approach does away with the need to duplicate
space
o As you cross a name off the original list, a free space opens up

o Instead of writing the minimum value on a second list, exchange it with the
value currently in the position where the crossed-off item should go

Bubble Sort

A selection sort that uses a different scheme for finding the minimum value
o Starting with the last list element, we compare successive pairs of elements,
swapping whenever the bottom element of the pair is smaller than the one
above it

Searching

A sequential search of a list begins at the beginning of the list and continues until the
item is found or the entire list has been searched

A binary search looks for an item in a list using a divide-and-conquer strategy

Binary Search

Binary Search Algorithm


o Binary search algorithm assumes that the items in the list being searched are
sorted
o The algorithm begins at the middle of the list in a binary search

o If the item for which we are searching is less than the item in the middle, we
know that the item wont be in the second half of the list
o Once again we examine the middle element (which is really the item 25% of
the way into the list)
o The process continues with each comparison cutting in half the portion of the
list where the item might be

Stacks

A stack is an abstract data type in which accesses are made at only one end
o LIFO, which stands for Last In First Out
o The insert is called Push and the delete is called Pop

Queues

A Queue is an abstract data type in which items are entered at one end and removed
from the other end
o FIFO, for First In First Out
o Like a waiting line in a bank or supermarket
o No standard queue terminology

Enqueue, Enque, Enq, Enter, and Insert


are used for the insertion operation

Dequeue, Deque, Deq, Delete, and Remove


are used for the deletion operation.

Searching is locating information in a table or file by


reference to a special field of each record called a key. The
goal of the search is to discover a record (if any) with a given
key value.
Sorting is to rearrange a set of items in ascending or
descending order. One reason that it is so useful is that it is
much easier to search for something in a sorted list than an
unsorted one.
Now imagine the words in the dictionary were not sorted.
Would you want to use it to search for the definition of a
word?
Without sorting, searching is impractical for very large sets of
data. You could apply the same principle to many other types
of data in the real world, such as the names in a phone book or
the books on the shelves of a library.
Additional information can be found in the text,
Understanding Computer Science for Advanced Level 3rd
Edition Chapter 15 page 317.
In this section, we will consider in detail several algorithms
for sorting and searching, along with several applications
where they play a critical role.

In computer science, linear search or sequential search is a


method for finding a particular value in a list, that consists of

checking every one of its elements, one at a time and in


sequence, until the desired one is found.
Pseudocode:
LinearSearch(array, size, key)
BEGIN
for i = 0 to size - 1
if (array[i] == key)
return i
endif
endfor
return -1
END
C Program:
#include<stdio.h>
int main(){
int a[10],i,n,key,c=-1;
printf("Enter the size of an array");
scanf("%d",&n);
printf("\nEnter the elements of the array");
for(i=0;i<=n-1;i++){
scanf("%d",&a[i]);
}
printf("\nThe elements of an array are");
for(i=0;i<=n-1;i++){
printf(" %d",a[i]);
}
printf("\nEnter the number to be search");
scanf("%d",&key);
for(i=0;i<=n-1;i++){
if(a[i]==key){
c=i;
break;
}
}
if(c==-1)

printf("\nThe number is not in the list");


else
printf("\nThe number is found");
return 0;
}

A fast way to search a sorted array is to use a binary search. The idea is to look at the element
in the middle. If the key is equal to that, the search is finished. If the key is less than the
middle element, do a binary search on the first half. If it's greater, do a binary search of the
second half.

Pseudocode:
BinarySearch(array, size, key)
BEGIN
low = 0
high = size
while (low + 1 < high)
test = (low + high)/2
if (array[test] > key)
high = test
else
low = test
endwhile
if (array[low] = = key
return low
else

return -1
END

C Program:
1.

#include<stdio.h>

2.

#include<conio.h>

3.

void main()

4.

5.

int a[10],n,i;

6.

int low,high,mid,key;

7.

clrscr();

8.

printf(enter the total numbers:");

9.

scanf(%d",&n);
printf(enter the array elements in ascending or
descending order:" );

10.

11.

for(i=0;i<n;i++)

12.

scanf(%d",&a[i]);

13.
14.

low=0;

15.

high=9;

16.

mid=(low+high)/2;

17.

printf(\nenter the number to be searched:");

18.

scanf(%d",&key);

19.

while(low<=high && a[mid]!=key)

20.

if(key<a[mid])

21.

high=mid-1;

22.
23.

else

24.

low=mid+1;

25.

mid=(low+high)/2;

26.

27.

If(a[mid]==key)
{

28.

printf(\nthe number is found at position


%2d",mid);

29.

30.
31.

else
{

32.
33.

printf(\nthe number is not found");


}

34.
35.

getch();

36.

This type of sorting is called "Selection Sort" because it works by repeatedly


selecting an element. It works as follows: first find the smallest element in the
array and exchange it with the element in the first position, then find the second
smallest element and exchange it with the element in the second position, and
continue in this way until the entire array is sorted.
Pseudocode:
SelectionSort(array)

BEGIN
for i = 1 to n-1
min_subsrcipt = i
min _value = array[i]
for j = i + 1 to n - 1
if (array[j] < min_value)
min_subscript = j
min_value = array[j]
endif
endfor
array[min_subscript] = array[i]
array[i] = min_value
endfor
END

Implementation
void
selectionSort(int numbers[], int array_size) { int i, j; int min, temp; for (i = 0; i <
array_size-1; i++) { min = i; for (j = i+1; j < array_size; j++) { if (numbers[j] <
numbers[min]) min = j; } temp = numbers[i]; numbers[i] = numbers[min];
numbers[min] = temp; } }

In the bubble sort, as elements are sorted they gradually

"bubble" (or rise) to their proper location in the array, like


bubbles rising in a glass of soda. The bubble sort repeatedly
compares adjacent elements of an array. The first and second
elements are compared and swapped if out of order. Then the
second and third elements are compared and swapped if out of
order. This sorting process continues until the last two
elements of the array are compared and swapped if out of
order. When this first pass through the array is complete, the
bubble sort returns to elements one and two and starts the
process all over again. So, when does it stop? The bubble sort
knows that it is finished when it examines the entire array and
no "swaps" are needed (thus the list is in proper order). The
bubble sort keeps track of occurring swaps by the use of a
flag.
The table below follows an array of numbers before, during,
and after a bubble sort for ascending order. A "pass" is defined
as one full trip through the array comparing and if necessary,
swapping, adjacent elements. Several passes have to be made
through the array before it is finally sorted.
Array at beginning: 6 4 6 5 1 3
After Pass #1: 4 6 5 1 3 6
After Pass #2: 4 5 1 3 6 6
After Pass #3: 4 1 3 5 6 6
After Pass #4: 1 3 4 5 6 6
After Pass #5 (done): 1 3 4 5 6 6
The bubble sort is an easy algorithm to program, but it is
slower than many other sorts. With a bubble sort, it is always
necessary to make one final "pass" through the array to check
to see that no swaps are made to ensure that the process is
finished. In actuality, the process is finished before this last
pass is made.

Pseudocode:
BubbleSort
BEGIN
for i = n - 1 to 1
for j = 1 to i
if (array[j] > array[j+1])
swap(array[j], array[j+1])
endif
endfor
endfor
END
C Program:
1. #include<stdio.h>
2. #include<conio.h>
3.

void bubble(int a[],int n)

int i,j,t;

for(i=n-2;i>=0;i--)

{
for(j=0;j<=i;j++)

{
if(a[j]>a[j+1])

t=a[j];

a[j]=a[j+1];

a[j+1]=t;

}//end for 1.

}//end function.

void main()

int a[100],n,i;

clrscr();

printf("\n\n Enter integer value for total no.s of eleme


nts to be sorted: ");
scanf("%d",&n);

for( i=0;i<=n-1;i++)
{ printf("\n\n Enter integer value for element no.
%d : ",i+1);

scanf("%d",&a[i]);
}

bubble(a,n);

printf("\n\n Finally sorted array is: ");

for( i=0;i<=n-1;i++)

printf("%3d",a[i]);

} //end program.

/*

--------SAMPLE OUTPUT---------------------

Enter integer value for total no.s of elements to be sorted:


6

Enter integer value for element no.1 : 89

Enter integer value for element no.2 : -4


Enter integer value for element no.3 : -67

Enter integer value for element no.4 : 5

Enter integer value for element no.5 : 78

Enter integer value for element no.6 : 11

Finally sorted array is: -67 -4 5 11 78 89

-----------------------------------------
*/

LIST IMPLEMENTATION USING ARRAY


#include<stdio.h>
#include<conio.h>
#define MAX 20 //maximum no of elements in the list
//user defined datatypes
struct
{

}l;

int
int
int
int

list[MAX];
element;//new element to be inserted
pos; //position of the element to be inserted or deleted
length; //total no of elements

enum boolean { true, false };


typedef enum boolean boolean;
//function prototypes
int menu(void); //function to display the list of operations
void create(void); //function to create initial set of elements
void insert(int, int); //function to insert the given element at specified
position
void delet(int);//function to delete the element at given position
void find(int); //function to find the position of the given element, if
exists
void display(void); //function to display the elements in the list
boolean islistfull(void);//function to check whether the list is full or
not
boolean islistempty(void); //function to check whether the list is empty or
not
void main()
{
int ch;
int element;
int pos;
l.length = 0;
while(1)
{
ch = menu();
switch (ch)
{
case 1:

case 2:

l.length = 0;
create();
break;
if (islistfull() != true)
{
printf("\tEnter the New element : ");
scanf("%d", &element);
printf("\tEnter the Position : ");

scanf("%d", &pos);
insert(element, pos);
}
else
{
insert");

printf("\tList if Full. Cannot


printf("\nPress any key to

continue...");

getch();
}
break;
case 3:

to be deleted :

if (islistempty() != true)
{
printf("Enter the position of element
");
scanf("%d", &pos);
delet(pos);
}
else
{
printf("List is Empty.");
printf("\nPress any key to

continue...");

getch();
}
break;
case 4:

l.length);

printf("No of elements in the list is %d",


printf("\nPress any key to continue...");
getch();
break;

case 5:
");

printf("Enter the element to be searched :


scanf("%d", &element);
find(element);
break;

case 6:
case 7:

display();
break;

exit(0);
break;
default:
printf("Invalid Choice");
printf("\nPress any key to continue...");
getch();
}

}
//function to display the list of elements
int menu()
{
int ch;
clrscr();
printf("\n\t\t********************************************\n");

printf("\t\t******LIST Implementation Using Arrays******\n");


printf("\t\t********************************************\n\n");
printf("\t1. Create\n\t2. Insert\n\t3. Delete\n\t4. Count\n\t5.
Find\n\t6. Display\n
\t7. Exit\n\n\tEnter your choice : ");
scanf("%d", &ch);
printf("\n\n");
return ch;
}
//function to create initial set of elements
void create(void)
{
int element;
int flag=1;
while(flag==1)
{
printf("Enter an element : ");
scanf("%d", &element);
l.list[l.length] = element;
l.length++;
printf("To insert another element press '1' : ");
scanf("%d", &flag);
}
}
//function to display the elements in the list
void display(void)
{
int i;
for (i=0; i<l.length; i++)
printf("Element %d : %d \n", i+1, l.list[i]);
printf("Press any key to continue...");
getch();
}
//function to insert the given element at specified position
void insert(int element, int pos)
{
int i;
if (pos == 0)
{
printf("\n\nCannot insert at zeroth position");
getch();
return;
}
if (pos-1 > l.length)
{
printf("\n\nOnly %d elements exit. Cannot insert at %d
postion", l.length,
pos);
printf("\nPress any key to continue...");
getch();
}
else
{
for (i=l.length; i>=pos-1; i--)
{
l.list[i+1] = l.list[i];
}

l.list[pos-1] = element;
l.length++;
}

//function to delete the element at given position


void delet(int pos)
{
int i;
if(pos == 0)
{
printf("\n\nCannot delete at zeroth position");
getch();
return;
}
if (pos > l.length)
{
printf("\n\nOnly %d elements exit. Cannot delete",
l.length, pos);
printf("\nPress any key to continue...");
getch();
return;
}
for (i=pos-1; i<l.length; i++)
{
l.list[i] = l.list[i+1];
}
l.length--;
}
//function to find the position of the given element, if exists
void find(int element)
{
int i;
int flag = 1;
for (i=0; i<l.length; i++)
{
if(l.list[i] == element)
{
printf ("%d exists at %d position",element, i+1);
flag = 0;
printf("\nPress any key to continue...");
getch();
break;
}
}
if(flag == 1)
{
printf("Element not found.\nPress any key to continue...");
getch();
}
}
//function to check whether the list is full or not
boolean islistfull(void)
{
if (l.length == MAX)
return true;

else

return false;

}
//function to check whether the list is empty or not
boolean islistempty(void)
{
if (l.length == 0)
return true;
else
return false;
}

Sample Output:
1. Create
2. Insert
3. Delete
4. Count
5. Find
6. Display
7. Exit
Enter your Choice: 1
Enter an element: 25
To insert another element press 1: 1
Enter an element: 50
To insert another element press 1: 0
Enter your Choice: 6
Element in the List are
1. 25
2. 50
Enter your Choice: 2
Enter an element: 5
Enter the position: 1
Element in the List are
1. 25
2. 50
Enter your Choice: 3
Enter the position: 3
Enter your Choice: 6
Element in the List are
1. 5
2. 25
Enter your Choice: 4
Number of Elements: 2
Enter your Choice: 7

CIRCULAR QUEUE IMPLEMENTATION USING ARRAYS


/*Program of queue using array*/
# include

# define MAX 5
int
int
int
int

queue_arr[MAX];
rear = -1;
front = -1;
count = 0;

int main()
{
int choice;
while(1)
{
printf("1.Enqueue\n");
printf("2.Dequeue\n");
printf("3.Display\n");
printf("4.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
enqueue();
break;
case 2 :
dequeue();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice\n");
}/*End of switch*/
}/*End of while*/
return 0;
}/*End of main()*/
enqueue()
{
int added_item;
if (count==MAX)
printf("Queue Overflow\n");
else
{
if (front==-1) /*If queue is initially empty */
front=0;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
rear=rear+1;
if (rear==MAX)
rear=0;
queue_arr[rear] = added_item ;
count++;
}
}/*End of insert()*/
dequeue()
{
if (front == -1 || count==0)

{
printf("Queue Underflow\n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_arr[front]);
front=front+1;
if (front==MAX)
front=0;
count--;
}
}/*End of del() */
display()
{
int i;
if (front == -1)
printf("Queue is empty\n");
else
{
printf("Queue is :\n");
for(i=front;i<= rear;i++)
printf("%d ",queue_arr[i]);
printf("\n");
}
}/*End of display() */

LINEAR QUEUE IMPLEMENTATION USING ARRAYS


/*Program of queue using array*/
# include
# define MAX 5
int
int
int
int

queue_arr[MAX];
rear = -1;
front = -1;
count = 0;

int main()
{
int choice;
while(1)
{
printf("1.Enqueue\n");
printf("2.Dequeue\n");
printf("3.Display\n");
printf("4.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
enqueue();
break;
case 2 :
dequeue();

case 3:

break;
display();
break;

case 4:

exit(1);
default:
printf("Wrong choice\n");
}/*End of switch*/
}/*End of while*/
return 0;
}/*End of main()*/
enqueue()
{
int added_item;
if (count==MAX)
printf("Queue Overflow\n");
else
{
if (front==-1) /*If queue is initially empty */
front=0;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
rear=rear+1;
queue_arr[rear] = added_item ;
count++;
}
}/*End of insert()*/
dequeue()
{
if (count == 0)
{
printf("Queue Underflow\n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_arr[front]);
count--;
if (count == 0)
front = -1;
else
for(i=0; i<rear; i++)
queue_arr[i] = queue_arr[i+1]
rear=rear-1;
}
}/*End of del() */
display()
{
int i;
if (front == -1)
printf("Queue is empty\n");
else
{
printf("Queue is :\n");
for(i=front;i<= rear;i++)
printf("%d ",queue_arr[i]);
printf("\n");

}
}/*End of display() */

STACK IMPLEMENTATION USING ARRAYS


/* Program of stack using array*/
#include
#define MAX 5
int top = -1;
int stack_arr[MAX];
main()
{
int choice;
while(1)
{
printf("1.Push\n");
printf("2.Pop\n");
printf("3.Display\n");
printf("4.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice\n");
}/*End of switch*/
}/*End of while*/
}/*End of main()*/
push()
{
int pushed_item;
if(top == (MAX-1))
printf("Stack Overflow\n");
else
{
printf("Enter the item to be pushed in stack : ");
scanf("%d",&pushed_item);
top=top+1;
stack_arr[top] = pushed_item;
}
}/*End of push()*/

pop()
{

if(top == -1)
printf("Stack Underflow\n");
else
{
printf("Popped element is : %d\n",stack_arr[top]);
top=top-1;
}
}/*End of pop()*/
display()
{
int i;
if(top == -1)
printf("Stack is empty\n");
else
{
printf("Stack elements :\n");
for(i = top; i >=0; i--)
printf("%d\n", stack_arr[i] );
}
}/*End of display()*/

You might also like