Vous êtes sur la page 1sur 13

ECX4265

Data Structures and Algorithms

TMA-2

W.J.T. Sumesh Lahiru Fernando


Reg. No.: 311090095
Due Date: 09-09-2011

ASSIGNMENT COVER SHEET

Name

W.J.T. Sumesh Lahiru Fernando

Registration Number

311090095

Bachelor of Software Engineering

Course

ECI4265 TMA-2

Due Date

09th September, 2011

Project Plan

Question 01 - 05 - (05/09/2011)

Answers for the; Q1 1.1 Runtime When dealing with increasingly large sets of data, inefficient sorting algorithms can become too slow for practical use within an application. Memory Space Faster algorithms that require recursive calls typically involve creating copies of the data to be sorted. Stability Stability, simply defined, is what happens to elements that are comparatively the same.

1.2 Sort Bubble Selection Insertion Shellsort Quicksort Mergesort Heapsort 1.3 i) ii) iii) In a Library we can keep books according to the Alphabetical order or we can section them by the Subject. So students can quickly find by the book name. In a mobile Contacts must be sorted to a Alphabetical order. So the user can find contacts easily. In Train/Bus/Air Line schedule it is very important to have a sorted Time Schedule. People can easily and quickly look at their schedule. Average O(N2) O(N2) O(N2) O(N3/2) O(N*logN) O(N*logN) O(N*logN) Worst O(N2) O(N2) O(N2) O(N3/2) O(N2) O(N*logN) O(N*logN) Comparison Poor Fair Good Good Fair Fair Extra Memory No No No No No Yes No

ECX4265 [TMA - 2]

Q2 2.1 for i = n down to 1 for j = 1 to i-1 if pages[j] < pages[j+1] swap(A,i,j) 2.2 The inner for loop (using j as the loop variable) is walking through the array looking at sequential entries and swapping them if they are out of order. First it will check the first and the second entries; then the second and the third; and so on. The main effect of that loop is that the largest element will end up in the last space that loop examines. The outer loop makes the inner loop happen n times. The first time, the largest number will be correctly positioned; the second time the next largest number will be correctly positioned and so on until the smallest number is correctly positioned. according to the example, this is how Bubblesort works. {140, 78, 230, 167, 172, 290} First two numbers Swaps. (If the Left side number bigger than the right side Number, move one position right) {140 78, .} {78, 148, 230, 167, 172, 290} {78, 148, 230, 167, 172, 290} {78, 148, 167, 230, 172, 290} {78, 148, 167, 230, 172, 290} {78, 148, 167, 172, 230, 290} {78, 148, 167, 172, 230, 290} 3.1 i) ii) iii) 3.2 Public void quick Sort (Int left, int right) { If(right-left<=0) // if size is 1 Return; //its already sorted Else //size is 2 or larger { // Partition Range Partition the array or sub array into left (smaller keys) and right (larger keys) groups. Call ourselves to sort the left group. Call ourselves again to sort the right group.

ECX4265 [TMA - 2]

Int partition = partition (left, right); Requick sortsort(partition+1); Requick sortsort(partition+1; right); } } 3.3

//soft left side //soft left side

public class quicksort { public static void main(String[]a) { int i; int array[]={3,27,12,63,94,89,78,42,50,36}; System.out.println("Quick Sort"); System.out.println("Befor Quick Sort"); for(i = 0; i < array.length; i++) System.out.println( array[i]+""); System.out.println(); quicksort(array,0,array.length-1); System.out.println("After:\n"); for(i = 0; i <array.length; i++); System.out.print(array[i]+""); System.out.println(); } public static void quicksort(int array[],int low, int n) { int lo = low; int hi = n; if (lo >= n); { return; } int mid = array [(lo + hi) / 2]; while (lo < hi) { while (lo<hi && array [lo] < mid); { lo++; } while (lo<hi && array[hi] > mid) { hi--; } if (lo < hi) { int T = array[lo]; array[lo] = array[hi]; array[hi] = T; } }

ECX4265 [TMA - 2]

} 3.4

if (hi < lo) { int T = hi; hi = lo; lo = T; } quicksort(array, low, lo); quicksort(array, lo == low ? lo+1 : lo, n); }

public class Quicksort private int[] numbers; private int number;

public void sort(int[] values) { // Check for empty or null array if (values ==null || values.length==0){ return; } this.numbers = values; number = values.length; quicksort(0, number - 1); } private void quicksort(int low, int high) { int i = low, j = high; // Get the pivot element from the middle of the list int pivot = numbers[low + (high-low)/2]; // Divide into two lists while (i <= j) { // If the current value from // element then get the next while (numbers[i] < pivot) { i++; } // If the current value from // element then get the next while (numbers[j] > pivot) { j--; } // // // // // if

the left list is smaller then the pivot element from the left list

the right list is larger then the pivot element from the right list

} } // Recursion if (low < j) quicksort(low, j);

If we have found a values in the left list which is larger then the pivot element and if we have found a value in the right list which is smaller then the pivot element then we exchange the values. As we are done we can increase i and j (i <= j) { exchange(i, j); i++; j--;

ECX4265 [TMA - 2]

if (i < high) quicksort(i, high);

private void exchange(int i, int j) { int temp = numbers[i]; numbers[i] = numbers[j]; numbers[j] = temp; }

Q4 4.1 Mergesort i) If the list is of length 0 or 1, then it is already sorted. Otherwise: ii) Divide the unsorted list into two sub lists of about half the size. iii) Sort each sub list recursively by re-applying the merge sort. iv) Merge the two sub lists back into one sorted list. Sort Mergesort Average O(N*logN) Worst O(N*logN) Extra Memory Yes

Quick Sort i) Partition the array or subarray into left (smaller keys) and right (larger keys) groups. ii) Call ourselves to sort the left group. iii) Call ourselves again to sort the right group. Sort Quicksort 4.2 MergeSort Array - A : {23, 47, 81, 95} Array - B : {7, 14, 39, 55, 62, 74} --------------------------------------------------------------------------------------------------------------------Average O(N*logN) Worst O(N2) Extra Memory No

ECX4265 [TMA - 2]

class MergeApp { public static void main(String[] args) { int[] arrayA = {23, 47, 81, 95}; int[] arrayB = {7, 14, 39, 55, 62, 74}; int[] arrayC = new int[10]; merge(arrayA, 4, arrayB, 6, arrayC); display(arrayC, 10); } // end main() //----------------------------------------------------------// merge A and B into C public static void merge( int[] arrayA, int sizeA, int[] arrayB, int sizeB, int[] arrayC ) { int aDex=0, bDex=0, cDex=0; while(aDex < sizeA && bDex < sizeB) // neither array empty if( arrayA[aDex] < arrayB[bDex] ) arrayC[cDex++] = arrayA[aDex++]; else arrayC[cDex++] = arrayB[bDex++]; while(aDex < sizeA) // arrayB is empty, arrayC[cDex++] = arrayA[aDex++]; // but arrayA isnt while(bDex < sizeB) // arrayA is empty, arrayC[cDex++] = arrayB[bDex++]; // but arrayB isnt }// end merge() //----------------------------------------------------------// display array public static void display(int[] theArray, int size) { for(int j=0; j<size; j++) System.out.print(theArray[j] + ); System.out.println(); } //----------------------------------------------------------} // end class MergeApp How MergeSort works in this sort In main() the arrays arrayA, arrayB, and arrayC are created; then the merge() method is called to merge arrayA and arrayB into arrayC, and the resulting contents of arrayC are displayed. Heres the output: 7 14 23 39 47 55 62 74 81 95 The merge() method has three while loops. The first steps along both arrayA and arrayB, comparing elements and copying the smaller of the two into arrayC. The second while loop deals with the situation when all the elements have been transferred out of arrayB, but arrayA still has remaining elements. (This is what happens in the example, where 81 and 95 remain in arrayA.) The loop simply copies the remaining elements from arrayA into arrayC. The third loop handles the similar situation when all the elements have been transferred out of arrayA, but arrayB still has remaining elements; they are copied to arrayC.

ECX4265 [TMA - 2]

4.3 1, 8, 6, 4, 10, 5, 3, 2, 22
public class Mergesort { private int[] numbers; private int number; public void sort(int[] values) { this.numbers = values; number = values.length; } mergesort(0, number - 1);

private void mergesort(int low, int high) { // Check if low is smaller then high, if not then the array is sorted if (low < high) { // Get the index of the element which is in the middle int middle = (low + high) / 2; // Sort the left side of the array mergesort(low, middle); // Sort the right side of the array mergesort(middle + 1, high); // Combine them both merge(low, middle, high); } } private void merge(int low, int middle, int high) { // Helperarray int[] helper = new int[number]; // Copy both parts into the helper array for (int i = low; i <= high; i++) { helper[i] = numbers[i]; } int i = low; int j = middle + 1; int k = low; // Copy the smallest values from either the left or the right side back // to the original array while (i <= middle && j <= high) { if (helper[i] <= helper[j]) { numbers[k] = helper[i]; i++; } else { numbers[k] = helper[j]; j++; } k++; } // Copy the rest of the left side of the array into the target array

ECX4265 [TMA - 2]

while (i <= middle) { numbers[k] = helper[i]; k++; i++; } helper = null; } }

Q5. 5.1 public int getItem(int[] list, int item) { for (int i = 0; i < list.length; i++) { if (list[i] == item) return i; } return -1; } 5.2 i) Two methods, called move-to-front and transposition, incorporating the modifications to the sequential search method are put forward to make the method more efficient. The technique is based on the concept that the file is continuously reordered such that the more frequently used records would be moved to the front and the less frequently used records would be moved to the back. In move-to-front method, whenever a record is retrieved, it is moved to the front of the file. In the transposition method, whenever a record is retrieved it is interchanged with the record preceding it. Both the methods are based on the assumption that the same records are retrieved again and again. Advancing those records to the front of the file makes the subsequent retrievals faster. But this reduces the search efficiency for other records. In transposition method, the record is advanced by one position each time it is retrieved. Advancement of the record to the front requires frequent retrievals. ii) The efficiency of searching can be improved by sorting the file to be searched. Number of comparisons, on the average, when the search key is absent from the file, is reduced by half of that for unsorted file. When there are several search requests, sorting the requests and the file facilitates the concurrent searching of all the requests. This avoids the searching of the entire file for each request.

10

ECX4265 [TMA - 2]

5.3 1. 2. location = -1; while ((more than one item in list) and (haven't yet found target)) 2A. look at the middle item 2B. if (middle item is target) have found target else 2C. if (target < middle item) list = first half of list 2D. else (target > middle item) list = last half of list end while if (have found target) location = position of target in original list return location as the result

3. 4. 5.4 (i)

Using sequential search

boolean found = false; int number =45; int k = 0; int[] test2 = {9, 12, 24, 30, 36, 45, 70}; while (!found && k < test2.length-1) { if (test2[k] == number) { found = true; } else { k += 1; } } System.out.println(); if (found) { System.out.println("Found in position " + k); } else { System.out.println("The number is not found"); }

11

ECX4265 [TMA - 2]

(ii)

Using binary search

int[] test3 = {9, 12, 24, 30, 36, 45, 70}; Arrays.sort(test3); // read key; print if not in whitelist int key = number; System.out.println(binarySearch(key, test3)); public static int binarySearch(int key, int[] a) { System.out.println("hello"); int lo = 0; int hi = a.length - 1; while (lo <= hi) { // Key is in a[lo..hi] or not present. int mid = lo + (hi - lo) / 2; if (key < a[mid]) hi = mid - 1; else if (key > a[mid]) lo = mid + 1; else return mid; } return -1; } 5.5 Binary Search Binary Search is an incredibly powerful technique for searching an ordered list. It is familiar to everyone who uses a telephone book! The basic algorithm is to find the middle element of the list, compare it against the key, decide which half of the list must contain the key, and repeat with that half. Two requirements to support binary search: * Random access of the list elements, so we need arrays instead of linked lists. * The array must contain elements in sorted order by the search key. Sequential Search The simplest algorithm to search a dictionary for a given key is to test successively against each element. This works correctly regardless of the order of the elements in the list. However, in the worst case all elements might have to be tested.

12

ECX4265 [TMA - 2]

W.J.T. Sumesh Lahiru Fernando


Reg. No.: 311090095

Vous aimerez peut-être aussi