Sunday, March 22, 2009

Sorting Algorithm

Sorting Algorithm

From Wikipedia, the free encyclopedia


In computer science and mathematics, a sorting algorithm is an algorithm that puts elements of a list in a certain order. The most-used orders are numerical order and lexicographical order. Efficient sorting is important to optimizing the use of other algorithms (such as search and merge algorithms) that require sorted lists to work correctly; it is also often useful for canonicalizing data and for producing human-readable output. More formally, the output must satisfy two conditions:



  1. The output is in nondecreasing order (each element is no smaller than the previous element according to the desired total order);

  2. The output is a permutation, or reordering, of the input.
(http://en.wikipedia.org/wiki/Sorting_algorithm)[1].


Summaries of popular sorting algorithms



Bubble sort


Main article: Bubble sort


Bubble sort is a straightforward and simplistic method of sorting data that is used in computer science education. The algorithm starts at the beginning of the data set. It compares the first two elements, and if the first is greater than the second, it swaps them. It continues doing this for each pair of adjacent elements to the end of the data set. It then starts again with the first two elements, repeating until no swaps have occurred on the last pass. While simple, this algorithm is highly inefficient and is rarely used except in education. For example, if we have 100 elements then the total number of comparisons will be 10000. A slightly better variant, cocktail sort, works by inverting the ordering criteria and the pass direction on alternating passes. Its average case and worst case are both O(n²).


Source Code
Below is the basic bubble sort algorithm.







void bubbleSort(int numbers[], int array_size)


{

int i, j, temp;



for (i = (array_size - 1); i >= 0; i--)

{

for (j = 1; j <= i; j++) { if (numbers[j-1] > numbers[j])

{

temp = numbers[j-1];

numbers[j-1] = numbers[j];

numbers[j] = temp;

}

}

}

}



(http://linux.wku.edu/~lamonml/algor/sort/bubble.html)[1].

Insertion sort


Main article: Insertion sort


Insertion sort is a simple sorting algorithm that is relatively efficient for small lists and mostly-sorted lists, and often is used as part of more sophisticated algorithms. It works by taking elements from the list one by one and inserting them in their correct position into a new sorted list. In arrays, the new list and the remaining elements can share the array's space, but insertion is expensive, requiring shifting all following elements over by one. Shell sort (see below) is a variant of insertion sort that is more efficient for larger lists.


Source Code
Below is the basic insertion sort algorithm.







void insertionSort(int numbers[], int array_size)


{

int i, j, index;



for (i=1; i < index =" numbers[i];" j =" i;">while ((j > 0) && (numbers[j-1] > index))

{

numbers[j] = numbers[j-1];

j = j - 1;

}

numbers[j] = index;

}

}


(http://linux.wku.edu/~lamonml/algor/sort/insertion.html)[2].

Shell sort


Main article: Shell sort


Shell sort was invented by Donald Shell in 1959. It improves upon bubble sort and insertion sort by moving out of order elements more than one position at a time. One implementation can be described as arranging the data sequence in a two-dimensional array and then sorting the columns of the array using insertion sort. Although this method is inefficient for large data sets, it is one of the fastest algorithms for sorting small numbers of elements (sets with fewer than 1000 or so elements). Another advantage of this algorithm is that it requires relatively small amounts of memory.


Source CodeBelow is the basic shell sort algorithm.


void shellSort(int numbers[], int array_size){


int i, j, increment, temp;
increment = 3;


while (increment > 0)


{ for (i=0; i < j =" i;" temp =" numbers[i];">= increment) && (numbers[j-increment] > temp)){ numbers[j] = numbers[j - increment];


j = j - increment; } numbers[j] = temp;


} if (increment/2 != 0) increment = increment/2;


else if (increment == 1)


increment = 0;


else increment = 1; }}


(http://linux.wku.edu/~lamonml/algor/sort/merge.html)[3].



Merge sort


Main article: Merge sort


Merge sort takes advantage of the ease of merging already sorted lists into a new sorted list. It starts by comparing every two elements (i.e., 1 with 2, then 3 with 4...) and swapping them if the first should come after the second. It then merges each of the resulting lists of two into lists of four, then merges those lists of four, and so on; until at last two lists are merged into the final sorted list. Of the algorithms described here, this is the first that scales well to very large lists, because its worst-case running time is O(n log n).


Source CodeBelow is the basic shell sort algorithm.


void shellSort(int numbers[], int array_size){


int i, j, increment, temp;
increment = 3;


while (increment > 0) {


for (i=0; i <>

j = i; temp = numbers[i];


while ((j >= increment) && (numbers[j-increment] > temp)) {


numbers[j] = numbers[j - increment];


j = j - increment; }


numbers[j] = temp; }


if (increment/2 != 0)


increment = increment/2;


else if (increment == 1)


increment = 0;


else increment = 1; }}


(http://linux.wku.edu/~lamonml/algor/sort/merge.html)[4].


Main article: Heapsort


Heapsort is a much more efficient version of selection sort. It also works by determining the largest (or smallest) element of the list, placing that at the end (or beginning) of the list, then continuing with the rest of the list, but accomplishes this task efficiently by using a data structure called a heap, a special type of binary tree. Once the data list has been made into a heap, the root node is guaranteed to be the largest element. When it is removed and placed at the end of the list, the heap is rearranged so the largest element remaining moves to the root. Using the heap, finding the next largest element takes O(log n) time, instead of O(n) for a linear scan as in simple selection sort. This allows Heapsort to run in O(n log n) time.


Source CodeBelow is the basic heap sort algorithm. The siftDown() function builds and reconstructs the heap.


void heapSort(int numbers[], int array_size){


int i, temp;
for (i = (array_size / 2)-1; i >= 0; i--)


siftDown(numbers, i, array_size);
for (i = array_size-1; i >= 1; i--) {


temp = numbers[0];


numbers[0] = numbers[i];


numbers[i] = temp;


siftDown(numbers, 0, i-1); }}
void siftDown(int numbers[], int root, int bottom){


int done, maxChild, temp;
done = 0; while ((root*2 <= bottom) && (!done)) {


if (root*2 == bottom) maxChild = root * 2;


else if (numbers[root * 2] > numbers[root * 2 + 1])


maxChild = root * 2; else maxChild = root * 2 + 1;
if (numbers[root] <>

temp = numbers[root];


numbers[root] = numbers[maxChild];


numbers[maxChild] = temp; root = maxChild; }


else done = 1; }}


(http://linux.wku.edu/~lamonml/algor/sort/heap.html)[5].



Quicksort


Main article: Quicksort


Quicksort is a divide and conquer algorithm which relies on a partition operation: to partition an array, we choose an element, called a pivot, move all smaller elements before the pivot, and move all greater elements after it. This can be done efficiently in linear time and in-place. We then recursively sort the lesser and greater sublists. Efficient implementations of quicksort (with in-place partitioning) are typically unstable sorts and somewhat complex, but are among the fastest sorting algorithms in practice. Together with its modest O(log n) space usage, this makes quicksort one of the most popular sorting algorithms, available in many standard libraries. The most complex issue in quicksort is choosing a good pivot element; consistently poor choices of pivots can result in drastically slower O(n²) performance, but if at each step we choose the median as the pivot then it works in O(n log n).


function quicksort(array)


var list less, greater


if length(array) ≤ 1 return array


select and remove a pivot value pivot from arrayfor each x in array


if x ≤ pivot then append x to lesselse append x to greater


return concatenate(quicksort(less), pivot, quicksort(greater))



Bucket sort


Main article: Bucket sort


Bucket sort is a sorting algorithm that works by partitioning an array into a finite number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. A variation of this method called the single buffered count sort is faster than the quicksort and takes about the same time to run on any set of data.


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 donext-sort(buckets[i])


return the concatenation of buckets[0], ..., buckets[n-1]



Radix sort


Main article: Radix sort


Radix sort is an algorithm that sorts a list of fixed-size numbers of length k in O(n · k) time by treating them as bit strings. We first sort the list by the least significant bit while preserving their relative order using a stable sort. Then we sort them by the next bit, and so on from right to left, and the list will end up sorted. Most often, the counting sort algorithm is used to accomplish the bitwise sorting, since the number of values a bit can have is small.



Distribution sort


Distribution sort refers to any sorting algorithm where data is distributed from its input to multiple intermediate structures which are then gathered and placed on the output. It is typically not considered to be very efficient because the intermediate structures need to be created, but sorting in smaller groups is more efficient than sorting one larger group.



Shuffle sort


Shuffle sort is a type of distribution sort algorithm (see above) that begins by removing the first 1/8 of the n items to be sorted, sorts them recursively, and puts them in an array. This creates n/8 "buckets" to which the remaining 7/8 of the items are distributed. Each "bucket" is then sorted, and the "buckets" are concatenated into a sorted array.

(http://en.wikipedia.org/wiki/Sorting_algorithm)[2].

Thursday, March 12, 2009

Programmer: Niel Jay F. Ehilla.

//declaring a constructor of a list Queue
public class Queue {
public int entrynum;
public String firstname;
public String lastname;
public char middlename;
public Queue next;
public Queue (int Enum, String Fname String Lname char M, ){
entrynum=Enum;
firstname=Fname;
lastname=Lname;
middlename=M;
}

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

/*a separate class which contains the methods of the data structure Queue implemented in a linked list*/
class QueueList
private Queue first;
private Queue last;
public QueueList()
{
first=null;
last=null;
}
//checking if the list has elements or not
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 (Enum);
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(001, “Niel jay”, “Ehilla” , ‘F’, )
theQueue.enqueue(002, “Rico”, “Jesyl”, ‘M’)
System.out.println(theQueue);
theQueue.enqueue(003, “Julie”, “Pabio”, ‘L’)
System.out.println(theQueue)

theQueue.dequeue(001);
System.out.println(theQueue);

System.out.println(theQueue);
}
}

Tuesday, February 24, 2009

IT 123A-Queue

Concept;

A queue (pronounced /kjuː/) 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. This makes the queue a First-In-First-Out (FIFO) data structure.
[1].>(google.com)http://en.wikipedia.org/wiki/Queue_(data_structure)

Illustration;







[2](google.com)http://images.google.com.ph/images?hl=en&q=Queue&um=1&ie=UTF-8&sa=N&tab=wi

Referrence;

http://www.google.com.ph/search?hl=en&q=Queue&meta=


Tuesday, February 17, 2009

IT 123A-Doubly Linked List

Concept;

Doubly Linked List-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...[1](google.com)-(http://en.wikipedia.org/wiki/Linked_list)...

Illustration;







Referrence;
http://www.google.com.ph/search?hl=en&q=Doubly+Linked+List&meta=
























Thursday, February 12, 2009

IT 123A-Double Ened

Concept;

Double-Ended LinkList- it is a first and last reference. It can be thearrangement of such qualities in every inputs that are available. (wiki,google)

Programer: Niel Jay F. Ehilla
Subject: Data Structure
Purpose: To know about Double-Ended LinkList

Code/Implementation;

public class Link{
private int idata;
private long ddata;
link next;

public Link (int nidata, long nddata){
iData=nidata;
dData=nddata;
}
}


public class FirstLastLink{
private LinkFirst;
private LinkLast;
public FirstLastLink(){
first=null;
last=null;
}
public boolean isEmpty(){
return(first&&last==null);
}
public void insertFirst(int nidata, long nddata){
Link newLink=new Link(nidata, nddata);
new.next=first;
first=newLink;
}
public void insertLast(int nidata, long nddata){
Link newLink=new Link(nidata,nddata);
newLink.next=last;
last=newLink;
}
public Link deleteFirst(int nidata, long nddata){
Link temp=first;
first=first.next;
return temp;
}
public Link deleteLast(int nidata, long nidata){
Link temp2=last;
last=last.next;
return temp2;
}
public void displaylist(){
System.out.print("The List(first--->last):");
Link current=first;
while(current!=null){
current.displaylink();
current=current.next;
}
Link current2=last;
while(current2!=null){
current2.displaylink();
current2=current2.next;
}
System.out.println(" ");
}
}

public class Apps{
public static void main(String[]args){

FirstLastList theList=new FirstLastList();

theList.insertFirst(001, 1,000,000);
theList.insertFirst(002, 2,000,000);
theList.insertFirst(003, 3,000,000);

theList.insertLast(09, 4,000);
theList.insertLast(25, 5,000);
theList.insertLast(28, 6,000);

System.out.println(theList);

theList.deleteFirst();
theList.deleteLast();

System.out.println(theList);
}
}

Reference;
http://www.google.com.ph/search?hl=en&q=doubly+link+list&meta=

Monday, February 2, 2009

IT 123A-Stack

A.) Definition/Concept
Stack- is an abstract data type and data structure based on the principle of Last In First Out. (google.com)
History;
The stack method of expression evaluation was first proposed in 1955 and then patented in 1957 by early German computer scientist Friedrich L. Bauer, (google.com)
Abstract data type;
As an abstract data type, the stack is a container of nodes and has two basic operations: push and pop.(google.com)
Operations;
In modern computer languages, the stack is usually implemented with more operations than just "push" and "pop". The length of a stack can often be returned as a parameter. Another helper operation top(also known as peek) can return the current top element of the stack without removing it from the stack.(google.com)
Implementation;
A typical storage requirement for a stack of n elements is O(n). The typical time requirement of O(1) operations is also easy to satisfy with a dynamic array or (singly) linked list implementation.

Ex.
class Stack(object):
def __init__(self):
self.stack_pointer = None
def push(self, element):
self.stack_pointer = Node(element, self.stack_pointer)
def pop(self):
e = self.stack_pointer.element
self.stack_pointer = self.stack_pointer.next
return e def peek(self):
return self.stack_pointer.element
def __len__(self):
i = 0
sp = self.stack_pointer
while sp:
i += 1
sp = sp.next
return i class Node(object):
def __init__(self, element=None, next=None):
self.element = element
self.next = next if __name__ == '__main__':
# small use example s = Stack()
[s.push(i) for i in xrange(10)]
print [s.pop() for i in xrange(len(s))] (google.com)
Hardware support;
stack in main memory;
Many CPUs have registers that can be used as stack pointers. Some, like the Intel x86, have special instructions that implicitly use a register dedicated to the job of being a stack pointer. Others, like the DEC PDP-11 and the Motorola 68000 family have addressing modes that make it possible to use any of a set of registers as a stack pointer. (google.com)
stack in registers;
The Intel 80x87 series of numeric coprocessors has a set of registers that can be accessed either as a stack or as a series of numbered registers. Sun's SPARC has a number of register windows organized as a stack which significantly reduces the need to use memory for passing function's arguments and return values. (google.com)

B.)illustration







C.) Reference
http://en.wikipedia.org/wiki/Stack_(data_structure