Thursday, March 12, 2009

Sorting Algorithm

1.)Description:

a.) Insertion sort is a simple sorting algorithm, a comparison sort in which the sorted array (or list) is built one entry at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.


a.)
Bucket sort, or bin sort, is a sorting algorithm that works by partitioning an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a cousin of radix sort in the most to least significant digit flavour. Bucket sort is a generalization of pigeonhole sort. Since bucket sort is not a comparison sort, the Ω(n log n) lower bound is inapplicable. The computational complexity estimates involve the number of buckets.

c.) Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing two items at a time and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort.

d.) Quicksort is a well-known sorting algorithm developed by C. A. R. Hoare that, on average, makes Θ(nlogn) (big O notation) comparisons to sort n items. However, in the worst case, it makes Θ(n2) comparisons. Typically, quicksort is significantly faster in practice than other Θ(nlogn) algorithms, because its inner loop can be efficiently implemented on most architectures, and in most real-world data, it is possible to make design choices which minimize the probability of requiring quadratic time. Quicksort is a comparison sort and, in efficient implementations, is not a stable sort.

e.) Heapsort (method) is a comparison-based sorting algorithm, and is part of the selection sort family. Although somewhat slower in practice on most machines than a good implementation of quicksort, it has the advantage of a worst-case Θ(n log n) runtime. Heapsort is an in-place algorithm, but is not a stable sort.

f.) Merge sort or merge_sort is an O(n log n) comparison-based sorting algorithm. In most implementations it is stable, meaning that it preserves the input order of equal elements in the sorted output. It is an example of the divide and conquer algorithmic paradigm. It was invented by John von Neumann in 1945.

g.) Shell sort is a sorting algorithm that is a generalization of insertion sort, with two observations:
  • insertion sort is efficient if the input is "almost sorted", and
  • insertion sort is typically inefficient because it moves values just one position at a time.
The Shell sort is named after its inventor, Donald Shell, who published the algorithm in 1959. Some older textbooks and references call this the "Shell-Metzner" sort after Marlene Metzner Norton, but according to Metzner, "I had nothing to do with the sort, and my name should never have been attached to it.

2.) pseudocode

a.)

insertionSort(array A)
begin
for i := 1 to length[A]-1 do
begin
value := A[i];
j := i-1;
while j ≥ 0 and A[j] > value do
begin
A[j + 1] := A[j];
j := j-1;
end;
A[j+1] := value;
end;
end;


b.)

function bucket-sort(array, n) is
buckets ← new array of n empty lists
for i = 0 to (length(array)-1) do
insert array[i] into buckets[msbits(array[i], k)]
for i = 0 to n - 1 do
next-sort(buckets[i])
return the concatenation of buckets[0], ..., buckets[n-1]


c.)

procedure bubbleSort( A : list of sortable items ) defined as:
do
swapped := false
for each i in 0 to length(A) - 2 inclusive do:
if A[ i ] > A[ i + 1 ] then
swap( A[ i ], A[ i + 1 ] )
swapped := true
end if
end for
while swapped
end procedure

or
procedure bubbleSort( A : list of sortable items ) defined as:
n := length( A )
do
swapped := false
n := n - 1
for each i in 0 to n - 1 inclusive do:
if A[ i ] > A[ i + 1 ] then
swap( A[ i ], A[ i + 1 ] )
swapped := true
end if
end for
while swapped
end procedure


d.)

function quicksort(array)
var list less, greater
if length(array) ≤ 1
return array
select and remove a pivot value pivot from array
for each x in array
if x ≤ pivot then append x to less
else append x to greater
return concatenate(quicksort(less), pivot, quicksort(greater))


e.)Zero Based

function heapSort(a, count) is
input: an unordered array a of length count

(first place a in max-heap order)
heapify(a, count)

end := count - 1
while end > 0 do
(swap the root(maximum value) of the heap with the last element of the heap)
swap(a[end], a[0])
(decrease the size of the heap by one so that the previous max value will
stay in its proper placement)
end := end - 1
(put the heap back in max-heap order)
siftDown(a, 0, end)

function heapify(a,count) is
(start is assigned the index in a of the last parent node)
start := (count - 2) / 2

while start ≥ 0 do
(sift down the node at index start to the proper place such that all nodes below
the start index are in heap order)
siftDown(a, start, count-1)
start := start - 1
(after sifting down the root all nodes/elements are in heap order)

function siftDown(a, start, end) is
input: end represents the limit of how far down the heap
to sift.
root := start

while root * 2 + 1 ≤ end do (While the root has at least one child)
child := root * 2 + 1 (root*2+1 points to the left child)
(If the child has a sibling and the child's value is less than its sibling's...)
if child + 1 ≤ end and a[child] <>then
child := child + 1 (... then point to the right child instead)
if a[root] <>then (out of max-heap order)
swap(a[root], a[child])
root := child (repeat to continue sifting down the child now)
else
return


f.)

function merge_sort(m)
var list left, right, result
if length(m) ≤ 1
return m

// This calculation is for 1-based arrays. For 0-based, use length(m)/2 - 1.
var middle = length(m) / 2
for each x in m up to middle
add x to left
for each x in m after middle
add x to right
left = merge_sort(left)
right = merge_sort(right)
result = merge(left, right)
return result

g.)

input: an array a of length n

inc ← round(n/2)
while inc > 0 do:
for i = inc .. n − 1 do:
tempa[i]
ji
while jinc and a[jinc] > temp do:
a[j] ← a[jinc]
jjinc
a[j] ← temp
inc ← round(inc / 2.2)



references:

["Wiki"] http://en.wikipedia.org/wiki/Bubble_sort

["Wiki"] http://en.wikipedia.org/wiki/Insertion_sort

["Wiki"] http://en.wikipedia.org/wiki/Shell_sort

["Wiki"] http://en.wikipedia.org/wiki/Heapsort

["Wiki"] http://en.wikipedia.org/wiki/Merge_sort

["Wiki"] http://en.wikipedia.org/wiki/Quicksort

["Wiki"] http://en.wikipedia.org/wiki/Bucket_sort


Implementation of QUEUE

/* Programmer’s name: Matet P. Tipudan 
Name of Program: Queue implementation
Date Started: March 13, 2009
Date Finished : March 13, 2009
Instructor : Mr. Dony Dongiapon
Course: IT 123: Data Structures
Objective: To be able to make a program that we can implement a queue data structure in a linked list.
*/


Concept: List of employees in a given company

//class constructor
class Queue{
public int employeenum;
public String firstname;
public String Lastname;
public char Middlename;
public Queue next;


public Queue (int Enum, String Fname, String Lname, char M; )
{

emlopyeenum=Enum;
firstname=Fname;
lastname=Lname;
middlename=M;
}


//displaying the elements on the list
public void displayQueue()
{
System.out.print(employeename +” “ + firstname +” “ +” “+middlename+ “ “ +: + lastname)
}
}


/*a separate class which contains the ,methods that would be used in implementing the program */
class QueueList
private Queue first;
private Queue last;
public QueueList()
{
first=null;
last=null;
}


//checking if the queue has elements
public Boolean isEmpty()
{
return (first==null);
}

//inserting an element on the queue
public void Enqueue(int Enum, String Fname, String Lname, char M,)

{
Queue newQueue= new Queue (int Enum, String Fname, String Lname, char M,)

if( isEmpty())
last = newQueue;
newQueue.next=first;
first=newQueue;
}


//deleting an element on the queue
public void Dequeue (int Enum)
{
Queue newQueue=new Queue (int Enum, String Fname, String Lname, char M)

int temp=first.entrynum;
if (first.next==null)
last=null;
first=first.next;
return temp


}
}


public class MainClass {
public static void main(String[] args) {
LinkQueue theQueue = new LinkQueue();
theQueue.enqueue(1, “Nemilyn”, “Bayacag”, ‘M’ )

theQueue.enqueue(2, “Lovely”, “Bajar”, ‘C’ );
System.out.println(theQueue);

theQueue.enqueue(3,“Nellen”, “Ortiz”, ‘C’ )
System.out.println(theQueue)



theQueue.dequeue(3);

System.out.println(theQueue);



System.out.println(theQueue);
}
}

Wednesday, February 18, 2009

Queue

/* Programmer: Matet P. Tipudan

Program name: Queue
Purpose: To implement a Queue Code.
Instructor: Dony Dongiapon
Subject: IT123 Data Structures*/


A. Definition/Concept:

♥A queue is a particular kind of collection in which the entities in the collection are kept in order and the principal (or only) operations on the collection are the addition of entities to the rear terminal position and removal of entities from the front terminal position.[Wikipedia]


B. Illustration:

C. References:

http://en.wikipedia.org/wiki/Queue_(data_structure)

Sunday, February 15, 2009

Stack Implementation

A. Definition/ Concept:

♥Always remember that the stack is a very common data structure used in programs. By data  structure, we mean something that is meant to hold data and provides certain operations on that data.[1]
♥Stacks are linear data structures. This means that their contexts are stored in what looks like a line (although vertically). This linear property, however, is not sufficient to discriminate a stack from other linear data structures. For example, an array is a sort of linear data structure in which you can access any element directly. In contrast, in a stack, you can only access the element at its top.[2]
♥Since a stack usually holds a bunch of items with the same type, we could implement a stack as an array. [www.google.com]


B. java Code:


//purpose: To implement an array of list in a certain Stack


public class LLStack{
private java.util.LinkedList list=nw java.util.LinkedList();
public LLStack(){
}
public void clear(){
list.clear();
}
public boolean isEmpty(){
return list.isEmpty();
}
public Object topEl(){
if(isEmpty())
throw new java.util.EmptyStackException();
return list.getLast();
}
public Object pop(){
if(isEmpty())
throw new java.util.EmptyStackException();
return list.removeLast();
}
public void push(Object el){
list.addLast(el);
}
public String toString(){
return list.toString();
}
}


C. References:

[1]Data structures and algorithms in Java 2nd Edition by: Adam Drozdek
[2]http://www.cs.bu.edu/teaching/c/stack/linked-list/

Friday, February 13, 2009

Doubly Linked Lists

A. Definition/ Concept

♥According to the book by: Mark Allen Weiss Doubly Linked Lists sometimes to traverse lists backwards. The standard implementation does not help here, but the solution is simple. Merely add an extra field to the data structure, containing a pointer to the previous cell. The cost of this is an extra link, which adds to the space requirement and also doubles the cost of insertions and deletions, because you no longer have to refer to a key by using a pointer to the previous cell.[Book of Data Structure and Algorithm Analysis]
♥According to Wikipedia, a more sophisticated kind of linked list is a doubly-linked list or two-way linked list. Each node has two links: one points to the previous node, or points to a null value or empty list if it is the first node; and one points to the next, or points to a null value or empty list if it is the final node.[WIKIPEDIA]


B.Illustration


Image:Doubly-linked-list.svg
A doubly-linked list containing three integer values: the value, the link forward to the next node, and the link backward to the previous node


C. java Code


//constructor class

class Link {

public int iData;

public Link next;

public Link previous;

public Link(int id) {

iData = id;

}

public String toString() {

return "{" + iData + "} ";

}

}

//a class that has the methods or operation of doubly linked list


class DoublyLinkedList {

private Link first;

private Link last;

public DoublyLinkedList() {

first = null;

last = null;

}

public boolean isEmpty() {

return first == null;

}

public void insertFirst(int dd) {

Link newLink = new Link(dd);

if (isEmpty()){

last = newLink;

}else{

first.previous = newLink;

}

newLink.next = first;

first = newLink;

}

public void insertLast(int dd) {

Link newLink = new Link(dd);

if (isEmpty()){

first = newLink;

}else {

last.next = newLink;

newLink.previous = last;

}

last = newLink;

}

public Link deleteFirst() {

Link temp = first;

if (first.next == null){

last = null;

}else{

first.next.previous = null;

}

first = first.next;

return temp;

}

public Link deleteLast() {

Link temp = last;

if (first.next == null){

first = null;

}else{

last.previous.next = null;

}

last = last.previous;

return temp;

}

public boolean insertAfter(int key, int dd) {

Link current = first;

while (current.iData != key) {

current = current.next;

if (current == null){

return false;

}

}

Link newLink = new Link(dd);

if (current == last) {

newLink.next = null;

last = newLink;

} else {

newLink.next = current.next;

current.next.previous = newLink;

}

newLink.previous = current;

current.next = newLink;

return true;

}

public Link deleteKey(int key) {

Link current = first;

while (current.iData != key) {

current = current.next;

if (current == null)

return null;

}

if (current == first){

first = current.next;

}else{

current.previous.next = current.next;

}

if (current == last){

last = current.previous;

}else{

current.next.previous = current.previous;

}

return current;

}

public String toString() {

String str = "List (first-->last): ";

Link current = first;

while (current != null) {

str += current.toString();

current = current.next;

}

System.out.println("");

System.out.print("List (last-->first): ");

current = last;

while (current != null) {

str += current.toString();

current = current.previous;

}

return str;

}

}


//main class that executes the operation on the doubly linked lists

public class MainClass {

public static void main(String[] args) {

DoublyLinkedList theList = new DoublyLinkedList();

theList.insertFirst(22);

theList.insertFirst(44);

theList.insertFirst(66);

theList.insertLast(11);

theList.insertLast(33);

theList.insertLast(55);

System.out.println(theList);

theList.deleteFirst();

theList.deleteLast();

theList.deleteKey(11);

System.out.println(theList);

theList.insertAfter(22, 77);

theList.insertAfter(33, 88);

System.out.println(theList);

}

}


D.References

[Book of Data Structure and Algorithm Analysis]Mark Allen Weiss
[WIKI]http://en.wikipedia.org/wiki/Linked_list
[WIKI]http://en.wikipedia.org/wiki/File:Doubly-linked-list.svg

Sunday, February 8, 2009

Double-ended Linked List

A. Definition/ Concept :

☻According to our previous topic Double-ended linked list, it was an addition reference that point to the last linked list and first linked list.


B. Illustration:










D. Reference:


[WIKI] http://www.rosettacode.org/wiki/Doubly-Linked_List_(element_insertion)


C. java Code:

class Link
{
public int iData;

public double dData:

public Link next;

public Link(int id,double dd)
{
iData = id;

dData=dd;}

public void displayLink()
{
System.out.print("{"+iData+","dData+"}");}}

class FirstLastList
{

private Link first;

private Link last;

public FirstLastList()
{

first = null;

last = null;
}
public boolean isEmpty()
{
return (first == null);
}
public void insertFirst(int id,double dd)
{
Link newLink = new Link(id,dd);
if (isEmpty ())

last = newLink;

newLink.next = first;

first = newLink;
}
public void insertLast(int id,double dd)
{

Link newLink = new Link(id,dd);

if (isEmpty())first = newLink;

elselast.next = newLink;

last = newLink;
}
public int deleteFirst()
{
int temp = first.iData;

if (first.next == null)

last = null;

first = first.next;

return temp;
}
public void displayList()
{
System.out.print("List(first-->Last);");

Link current=first;

while(current!=null)
{
current.displayLink();

current=current.next;
}
}
System.out.println(" ");
}
}
public class FirstLastApp
{
public static void main(String[] args)
{
FirstLastList theList = new FirstLastList();

theList.insertFirst(22,2.99);

theList.insertFirst(44,4.99);

theList.insertFirst(66,6.99);

theList.insertLast(11,1.99);

theList.insertLast(33,3.99);

theList.insertLast(55,5.99);

System.out.println(theList);

theList.deleteFirst();

theList.deleteFirst();

System.out.println(theList);
}
}

D. Reference:

[WIKI] http://www.rosettacode.org/wiki/Doubly-Linked_List_(element_insertion)

Monday, February 2, 2009

Stack


A. Definition/ Concept

♀According to Wikipedia page stack is container nodes and has two basic operations: push and pop. Push adds a given node to the top of the stack leaving previous nodes below. Pop removes and returns the current top node of the stack.

♀In computer science, a stack is an abstract data type and data structures based on the principle of Last in First Out. Example of this is, a modern Personal Computer uses stacks at the architecture level, which are used in the basic design of an operating system for interrupt handling and operating system function calls. ["Wikipedia"]

B. Illustration



File:Data stack.svg

Figure 1 illustration of the stack["Wikipedia"]