Data Structures & Algorithms

December 17, 2018 | Author: Nilshan Silva | Category: String (Computer Science), Array Data Structure, Algorithms, Software Engineering, Applied Mathematics
Share Embed Donate


Short Description

Studies the various Data Structures and Algorithms to unleash their performance and suitability....

Description

Assignment Brief BTEC Level 4-5 HNC/HND Diploma (QCF) To be filled by the Learner Name of the Learner

:

Edexcel No

:

Centre No :

Batch:

Date of Submission : Unit Assessment Information Qualification

: Higher National Diploma in Computing and Systems Development

Unit Code & Title

: H/601/1456– Unit 34 - Data Structures and Algorithms

Assessment Title & No’s : Understand and implement Data structures and Strings (No 1 of 1) Learning outcomes and grading opportunities: LO 01: Understand data structures and algorithms LO1.1

Learning

LO1.2

LO 1.3

Outcomes LO 02: Be able to implement data structures and algorithms LO2.1

Learning

LO2.2

LO 2.3

Outcomes LO 03: Understand how strings are structured and processed. LO3.1

Learning

LO3.2

Outcomes Assessor

: Ms. J. Menaka

Internal Examiner (IE)

:

Mr.

Praveen

Mahendran Date Reviewed : 25/04/2013

Date of IE

: 25/04/2013

Date : 08/06/2013 MeritIssued and Distinction Descriptor

Date Due

: 30/06/2014

M1

M2

M3

D1

D2

D3

All rights reserved ©ESOFT Metro Campus, Sri Lanka

Page 1 of 52

Statement of Originality and Student Declaration

I hereby, declare that I know what plagiarism entails, namely to use another’s work and to present it as my own without attributing the sources in the correct way. I further understand what it means to copy another’s work. 1. I know that plagiarism is a punishable offence because it constitutes theft. 2. I understand the plagiarism and copying policy of the Edexcel UK. 3. I know what the consequences will be if I plagiaries or copy another’s work in any of the assignments for this program. 4. I declare therefore that all work presented by me for every aspects of my program, will be my own, and where I have made use of another’s work, I will attribute the source in the correct way. 5. I acknowledge that the attachment of this document signed or not, constitutes a binding agreement between myself and Edexcel UK. 6. I understand that my assignment will not be considered as submitted if this document is not attached to the attached.

Student’s Signature: ……………………………

All rights reserved ©ESOFT Metro Campus, Sri Lanka

Date:.………………

Page 2 of 52

Task 1 A palindrome is a phrase that reads the same forwards as it does backwards. For example, “a man, a plan, a canal, Panama,” is a palindrome. 1.1. Write a program that figures out whether one string is a palindrome. The program should ignore white space and punctuation. (LO3.2)(D3.4) For example: "a man, a plan, a canal, Panama" is a palindrome. "Don’t nod" is a palindrome. "Taco Cat!" is a palindrome. 1.2. Create an Example Stack class for this problem. Use LinkedList, ArrayList or an array to implement the Stack.(LO 1.1) 1.3. Identify and implement opportunities for error handling and reporting. (LO 2.2) 1.4. Test the above application with a suitable test cases (LO 2.3) 1.5. Prepare a user manual for the developed solution to assist the users to work with it.(M3) Task 2 London Met University provides apartments to undergraduate students. The housing system uses a waiting list for apartment allocation. According to the university policy, when a possible match between applicant and apartment is found, the applicant is contacted via email or phone call and must decide whether to accept the apartment. If the applicant does not accept, he or she is placed back of the waiting list, and must wait again. We will simulate this process using a queue, and simplify the rules. Moreover, we will ignore the realistic constraints of the applicants, and simply have each applicant store a quality threshold for the apartment quality (a random number between 0 and 100). We will also assume that each apartment, once accepted, will be occupied for a random number of school years between 1 and 3. Assume k students apply for housing each school year. Each student node should contain an ID number to keep track. Get k from the user via command line arguments. Insert apartment details through the keyboard. Each apartment should have an ID number, quality score (a random number between 0 and 100) The assignment process should remove a student from the queue if the student “accepts” the apartment (is the apartment’s quality value above the student’s threshold?). If the student accepts then delete the student node. If the student rejects the apartment delete the student, insert him to the back of the queue and compare next student and repeat. This process repeats until all students are housed. 2.1. Write your own implementation of the queue by using a linked list for this problem with all the queue operations (enque, deque,etc). (LO 1.1) 2.2. Test the above application with a suitable test cases (LO 2.3) Task 3

All rights reserved ©ESOFT Metro Campus, Sri Lanka

Page 3 of 52

3.1 Implement Binary search using recursive algorithm and non-recursive algorithm, and compare the performance. (LO 1.2) (LO 1.3) 3.2. Sort the array given below with two different algorithms and compare the performance. {10, 30, 20, 45, 85, 90, 75} (LO 1.2) 3.3. Explain common string operations such as concatenation, substring, trim etc., also state their practical applications.(LO 3.1)

All rights reserved ©ESOFT Metro Campus, Sri Lanka

Page 4 of 52

Assessment Criteria (Students are not authorized to modify or write anything on below) Outcomes/Criteria for PASS

Possible evidence

Page

Feedback

LO1 Understand data structures and algorithms 1.1 produce design specification for data structures explaining the valid operations that can be carried out on the structures 1.2 explain the operation and performance of sorting and search algorithms 1.3 explain the operation of recursive algorithms and identify situations when recursion is used

Task 1.1, Task 2.1 Task 3.1, Task 3.2 Task 3.2

LO2 Be able to implement data structures and algorithms 2.1 implement data structures in an executable programming language in the context of well-defined problems

2.2 implement opportunities for error handling and

Task 1.2,Task 2.1 Task 1.3

Reporting

2.3 test results to enable comparison with expected results

Task 1.4,Task 2.2

LO3 Understand how strings are structured and processed. 3.1 explain common string operations and their practical applications

3.2 demonstrate the outcome of string operations in specified algorithms.

Task 3.3 Task 1.1 Task 3.3 Task 1.1

All rights reserved ©ESOFT Metro Campus, Sri Lanka

Page 5 of 52

Grade Descriptor for MERIT M1 Identify and apply strategies to find appropriate solutions

Possible evidence Task 3.2

M1.3

Compare different algorithms for

an effective approach to study and research has been

Feedback

Task 3.3 searching and sorting

Applied

Search

about

different

string

operations M2

Select / design appropriate methods / techniques

M2.3

a range of sources of information has been used

Task 3 Proper use of Harvard Referencing Search

about

different

string

operations M3

Present and communicate appropriate findings

Task 1.5 Documentation is well structured

M3.1

the appropriate structure and approach has been used.

adhering to the formatting guidelines with non-overlapping facts. Data provided about the company are accurate, reliable and consistent

All rights reserved ©ESOFT Metro Campus, Sri Lanka

Page 6 of 52

Grade Descriptor for DISTINCTION D1 Use critical reflection to evaluate own work and justify valid conclusions

Possible evidence Report: shown in the self-reflection section, good conclusion with suggestions for further improvement

Feedback

D1.1

conclusions have been arrived at through synthesis of ideas and have been justified

D2

D2.3

Take responsibility for managing and organizing activities

Undertaken Activities from 01 – 05 as mentioned in the observation sheet

Activities have been managed Submitted the work on time

D3

Demonstrate convergent / lateral / creative thinking

D3.4

problems have been solved.

Task 1.1, Task 2.1, Task 3.1, Task 3.2

All rights reserved ©ESOFT Metro Campus, Sri Lanka

Page 7 of 52

Strengths:

Weaknesses:

Future Improvements & Assessor Comment:

All rights reserved ©ESOFT Metro Campus, Sri Lanka

Page 8 of 52

Assessor:

Signature:

Date: ____/____/______

Signature:

Date: ____/____/______

Internal Verifier’s Comments:

Internal Verifier:

All rights reserved ©ESOFT Metro Campus, Sri Lanka

Page 9 of 52

Practical Observation Sheet Module: Data Structures and Algorithms Unit No: 34 Student Name: _________________________________

Activity

Activity

No 1

2

Learning Outcome (LO)

Provide evidence of coding, and explain a piece of coding to the audience.

LO 2.1

Run the solution

LO 2.1

Date

Signature

LO 3.2

LO 3.2

3

Test the solution with random data

LO 2.3

4

Prove the use of Error Controlling Mechanism in the solution and Error reporting structure

LO 2.2

5

Compare the performance of different algorithms

D2

Comments:

Assessor Name

:

Date

:

Signature

:

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

10

Table of Contents Table of Contents ................................................................................................................. xi Content of the Figures ....................................................................................................... xiii Acknowledgement ............................................................................................................... xv Task 01 ........................................................................................................................ 16 1.1 ........................................................................................................................................ 16 1.2 ........................................................................................................................................ 18 1.3 ........................................................................................................................................ 21 1.4 ........................................................................................................................................ 22 1.5 ........................................................................................................................................ 23 1.5.1 The User Manual .................................................................................................... 23 Task 02 ........................................................................................................................ 27 2.1 ........................................................................................................................................ 27 2.2 ........................................................................................................................................ 32 Task 03 ........................................................................................................................ 34 3.1 ........................................................................................................................................ 34 3.1.1 Binary Search Algorithm ........................................................................................ 34 3.1.2 Performance comparisons of Binary Searching Algorithms .................................. 37 3.2 ........................................................................................................................................ 38 3.2.1 Simple Sorting Algorithms ..................................................................................... 38 3.2.2 Divide and Conquered Algorithms ......................................................................... 40 3.2.3 Performance Comparison of Simple Sorting with Divide and Conquer

Sorting

Algorithms ....................................................................................................................... 42 3.3 ........................................................................................................................................ 42 3.3.1 Sub-Strings ............................................................................................................. 42 3.3.2 Concatenation ......................................................................................................... 44 3.3.3 Trim Method ........................................................................................................... 45 Appendices .......................................................................................................................... 46 Appendix A: Conclusion ................................................................................................. 46 Appendix B: Self-Reflection ........................................................................................... 47 Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

xi

Appendix C: The Gantt Chart.......................................................................................... 48 References ........................................................................................................................... 49 Bibliography ........................................................................................................................ 52

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

xii

Content of the Figures Figure 1: Java code to determine whether a word is a Palindrome (Part 1). ....................... 16 Figure 2: Java code to determine whether a word is a Palindrome (Part 2). ....................... 17 Figure 3: Stack Class beginning. ......................................................................................... 18 Figure 4: Push method in Stack class. ................................................................................. 19 Figure 5: Pop method in Stack class. ................................................................................... 19 Figure 6: Peek method and end of Stack class. ................................................................... 20 Figure 7: Try Catch and Exception handling....................................................................... 21 Figure 8: Importing the Project ........................................................................................... 24 Figure 9: Starting the Program ............................................................................................ 25 Figure 10: Working with the Program ................................................................................. 26 Figure 11: Quitting the Program .......................................................................................... 26 Figure 12: Int Single Linked List Node ............................................................................... 27 Figure 13: Java code for Queue class .................................................................................. 27 Figure 14: Enque method in Queue class ............................................................................ 28 Figure 15: Deque method in Queue class ............................................................................ 28 Figure 16: Java code for Single Linked List........................................................................ 29 Figure 17: Remove Head method in Single Linked List class ............................................ 29 Figure 18: Main class for the queue .................................................................................... 30 Figure 19: Get Student ID method in Queue Main class ..................................................... 30 Figure 20: Get Room ID method in Queue Main class ....................................................... 31 Figure 21: Get Room Score method in Queue Main class .................................................. 31 Figure 22: Get Choice method in Queue Main class ........................................................... 32 Figure 23: Recursive Binary Search Function ..................................................................... 35 Figure 24: Main Method which calls the search function ................................................... 35 Figure 25: Non-Recursive Binary Searching Algorithm ..................................................... 36 Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

xiii

Figure 26: Main method of Non-Recursive Binary Searching Algorithm .......................... 37 Figure 27: Insertion Sort Algorithm .................................................................................... 39 Figure 28: Main method and Sort method in Merge Sort Algorithm .................................. 40 Figure 29: Do Merge Sort method in Merge Sort Algorithm .............................................. 41 Figure 30: Merge Parts method in Merge Sort Algorithm .................................................. 41 Figure 31: Substring and related methods ........................................................................... 43 Figure 32: Concatenation using the '+' operator .................................................................. 44 Figure 33: Concatenation of strings by append method ...................................................... 44 Figure 34: Concatenation of strings through the concat method ......................................... 45 Figure 35:String Trim method in java ................................................................................. 45

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

xiv

Acknowledgement It is worth mentioning the names of my beloved lecturers including Miss Malsha Sethunge who helped a lot on completing this assignment on time. Special thanks to Mrs. Nimesha Rajakaruna for all the countless hours spent reviewing, helping, and explaining where necessary in making this a successful and accurate document. Finally, my friends require thanksgiving for helping and supporting me on occasion.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

xv

Task 01 1.1 Write a program that figures out whether one string is a palindrome. The program should ignore white space and punctuation. (LO3.2) (D3.4)

Figure 1: Java code to determine whether a word is a Palindrome (Part 1).

Source: Author’s work.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

16

Figure 2: Java code to determine whether a word is a Palindrome (Part 2).

Source: Author’s work.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

17

1.2 Create an Example Stack class for this problem. Use LinkedList, ArrayList or an array to implement the Stack. (LO 1.1)

Figure 3: Stack Class beginning.

Source: Author’s work.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

18

Figure 4: Push method in Stack class.

Source: Author’s work.

Figure 5: Pop method in Stack class.

Source: Author’s work.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

19

Figure 6: Peek method and end of Stack class.

Source: Author’s work

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

20

1.3 Identify and implement opportunities for error handling and reporting. (LO 2.2)

Figure 7: Try Catch and Exception handling.

Source: Author’s work.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

21

1.4 Test the above application with a suitable test cases (LO 2.3) Table 1: Test results for the program. Expected Test Test Case Case Outcome ID

Actual Outcome

Status

01

Try to input Null value

Display an error message as ‘You didn’t type anything’.

02

Input words less than 3 letters in length

Display an error message as ‘Type at least 3 letters to check’.

Pass

Input a nonpalindrome

Display a message as ‘The text you entered is not a Palindrome’.

Pass

04

Input a Palindrome

Display a message as ‘It’s a palindrome’.

Pass

05

Input words with spaces

Spaces ignored

Pass

06

Input words containing Punctuation marks.

Punctuation marks ignored

Pass

03

Pass

Source: Author’s work.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

22

1.5 Prepare a user manual for the developed solution to assist the users to work with it. (M3)

1.5.1 The User Manual This manual assumes that the user is familiar with performing some basic operations inside the NetBeans IDE and has enough knowledge to follow up with an assisted screen on a CLI like output console. The user should have a working version of the NetBeans IDE to launch this application and therefore access it. 

Setting Things Up

The program uses the NetBeans IDE’s built in output console in order to communicate with the user, therefore it is critical for the source of the program to be imported as a project in the IDE. To import the program, first copy the project folder that came with the drive into one of the directories of the computer. Then launch the NetBeans desktop application. Click ‘File’ from the splitter containers found on top right of the IDE and click ‘Open Project’ in the menu that scrolls down as shown through the figure 8. Watch for the pop up window that appears and use it to navigate to the copied folder containing the project on the computer and select the appropriate project. Click on the ‘Open Project’ button to finish importing and to open the selected project in the IDE.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

23

Figure 8: Importing the Project

Source: Author’s work. 

Using the Program

Once the project is imported and ready to use, click ‘Debug’ on the splitter containers found on top of the IDE and click on ‘Debug Project’ in the menu that scrolls down as shown through the figure 9 below. The program will now run on the output console which will appear near the bottom of the IDE.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

24

Figure 9: Starting the Program

Source: Author’s work. The output console would now display a line of text as “Enter Something”. Try entering a palindrome which has to be at least 3 characters in length, and press enter to see whether it is a palindrome or not. Any punctuation marks or white spaces are ignored by the program and would instead focus on the word being entered. Once a cycle is finished where the user enters something to check whether it’s a palindrome, it would start the cycle again automatically giving the option to perform the above operation continuously. This scenario has been illustrated in the figure below.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

25

Figure 10: Working with the Program

Source: Author’s work. The program will run in an endless loop until it is quitted by its user. To quit the program, click ‘Run’, again at the top of the IDE, and click ‘Stop Build/Run’ to safely stop the program from running as shown through the image below. For further assistance, click ‘Help’ from the top most splitter containers to find a range of help options right from the IDE or from the internet.

Figure 11: Quitting the Program

Source: Author’s work.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

26

Task 02 2.1 Write your own implementation of the queue by using a linked list for this problem with all the queue operations (enque, deque, etc.). (LO 1.1)

Figure 12: Int Single Linked List Node

Source: Author’s work.

Figure 13: Java code for Queue class

Source: Author’s work. Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

27

Figure 14: Enque method in Queue class

Source: Author’s work.

Figure 15: Deque method in Queue class

Source: Author’s work.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

28

Figure 16: Java code for Single Linked List

Source: Author’s work.

Figure 17: Remove Head method in Single Linked List class

Source: Author’s work.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

29

Figure 18: Main class for the queue

Source: Author’s work.

Figure 19: Get Student ID method in Queue Main class

Source: Author’s work.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

30

Figure 20: Get Room ID method in Queue Main class

Source: Author’s work.

Figure 21: Get Room Score method in Queue Main class

Source: Author’s work.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

31

Figure 22: Get Choice method in Queue Main class

Source: Author’s work.

2.2 Test the above application with a suitable test cases (LO 2.3)

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

32

Table 2: Test results for the Queue program

Test Case ID

Test Case

Expected Outcome

Actual Outcome

Status

1

Insert 1 as Display choice for message as room “Room has acceptance been assigned”

Pass

2

Insert 0 as Display choice for message as room “Please wait acceptance in the Queue”

Pass

3

Insert integer value other than 0 or 1 as choice for room acceptance

Display message as “Only 1 and 0 is valid”

Pass

4

Insert string value as choice for room acceptance

Display message as “Enter an integer value as the choice”

Pass

5

Insert string Display value as room message as score “Please enter an integer value as the score”

Pass

6

7

Insert integer value greater than 100 for room score

Display message as “Enter a value below 100 for the score”

Pass

Insert string Display value for message as student ID “The value entered is not an integer”

Pass

Source: Author’s work.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

33

Task 03 3.1 Implement Binary search using recursive algorithm and non-recursive algorithm, and compare the performance. (LO 1.2) (LO 1.3)

3.1.1 Binary Search Algorithm Among other types of searching mechanisms, binary search algorithm is a powerful searching algorithm which searches an input key at half intervals of a sorted array. It would then compare the value of the input key with the middle element value of the array to return the index of the middle element in case of a matching value, or to repeat the process in case of an unmatched value (Stoimen 2011). Unlike many sequential algorithms which searches from the beginning to end, binary search algorithm benefits from reduced working data sets where it divides the working range in halves in each comparison resulting in a highly efficient algorithm. Binary search algorithms are further classified as recursive binary search and non-recursive binary search algorithms as explained through the following points. 

Recursive Binary Searching Algorithm

A recursive binary searching algorithm is a function which accepts the array, the target value, the lower bound, and the upper bound as arguments to carry out the necessary calculations to compare the target value against the array as mentioned above. If the target value is found, the function returns the index from which the target value was found in the array. If the target value is not found, the function calls itself assigning new values that resulted from the previous comparison as arguments, and the function is recursively called until the target value is found. If the target value is not found after all possibilities are checked, or if the lower bound is greater than the target value in case of an array sorted in ascending order, -1 is returned to indicate the absence of the target value in the array (Forrest 2016). The 2 images below show how recursive binary searching is implemented in java code.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

34

Figure 23: Recursive Binary Search Function

Source: Author’s work adopted from Tripathi (2014).

Figure 24: Main Method which calls the search function

Source: Author’s work. The above code shows that, if the target value is greater than the mid value, then the lower bound is assigned with the mid value plus one. Else, the upper bound is assigned with mid value minus one. Thus the two indexes are used to pass the array to the same function where it now focuses only on the specified area.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

35



Non-Recursive Binary Searching Algorithm

Unlike the recursive approach, the non-recursive binary search uses iterations to perform the same function yet without the need for calling the function recursively. At each iteration, a different section of the array is being compared till the key value is matched. If the key value is matched its index is returned, else the iteration continues. In case of an array sorted in ascending order, the condition for looping is set to be below or equal to the upper bound. If that condition is failed, the iteration stops and return -1 to indicate the absence of the target value in the array. The image below shows this approach being implemented in the java language. Note that the last index or the first index are not required as arguments for the method, because the method is not recursively used and could calculate the values within the method itself.

Figure 25: Non-Recursive Binary Searching Algorithm

Source: Author’s work adopted from Abualrob (2010) & Damier (2015).

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

36

Figure 26: Main method of Non-Recursive Binary Searching Algorithm

Source: Author’s work.

3.1.2 Performance comparisons of Binary Searching Algorithms The two types of binary searching approaches introduced above are very similar to each other in terms of both functionality and program logic where they result in the same goal being achieved. However, recursive and non-recursive binary searching algorithms shows variations when compared for their performance where they differentiate themselves with respect to the measurements. Even though it feels intuitive that iterative approach might have some form of an advantage over the other, performance tests carried out by Knight (2013) shows contradictions, where it was assumed that recursive approach perform well over the non-recursive approach. Swartz (2003) shows that even though non-recursive is always usually faster, simpler, and uses less memory, recursive method is better at certain areas such as tree traversals. When compared for performance and efficiency, the recursive binary searching results in a logarithmic performance of 0(1) in terms of average time complexity compared to that of the 0(log n) worst case performance of non-recursive binary search algorithms (C Programming 2011). Therefore, it is evident that recursive binary search algorithms are more efficient than non-recursive binary search algorithms.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

37

3.2 Sort the array given below with two different algorithms and compare the performance. {-10, 30, 20, 45, 85, 90, 75} (LO 1.2)

3.2.1 Simple Sorting Algorithms In simple sorting techniques, an incrementally increasing boundary of sorted data on an array or data set could be imagined. The incrementing stops when all the data are sorted. These types of sorting require the new item and the data that have already been sorted to be potentially compared at each increment (Ruehr 1998). The following point describes an example of a simple sorting algorithm which leverages these techniques. 

Insertion Sort

Insertion sorting algorithms act in such a way that it picks up a key from the array and compare the key with the elements ahead of it and place the key in the correct position. The procedure iterates until all the elements in the array are sorted, usually in a left to right direction where the algorithm often chooses the second element of the array as the key (Ryerson University 2004). The image below provides an example of this algorithm in java code.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

38

Figure 27: Insertion Sort Algorithm

Source: Author’s work. Even though this algorithm is inefficient for sorting large data sets, it is very efficient at sorting small data sets and has one of the simplest implementations. According to Beniwal et al. (2016), insertion sorting requires just a single additional memory space where it becomes less space complex and is adaptive and stable making it overall better than selection sort or bubble sort algorithms.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

39

3.2.2 Divide and Conquered Algorithms The divide and conquer approach for sorting data sets is a highly efficient method in which the problem is divided into sub problems so that individual sub-problems become less complex where it could be solved recursively. The data for the next step is always saved. When the sub-problems are manageable, they are solved in a straightforward manner. These sub-problems are then combined to each other to form the solution of the original problem (Cormen et al. 2009). The following point describes an important algorithm which uses the divide and conquer approach. 

Merge Sort

Merge Sort algorithm is one of the first sorting algorithms. The key to this process is merging 2 sorted arrays into a third party. This process can be used to merge 2 sorted halves on the same array into a single array. The array is divided recursively into halves until the size becomes one. Then each half is compared and sorted where they are merged with other subarrays to complete the merging process resulting in a sorted array (Geeks for Geeks 2016). Java code for merge sort algorithm is shown through the 3 images below.

Figure 28: Main method and Sort method in Merge Sort Algorithm

Source: Author’s work. Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

40

Figure 29: Do Merge Sort method in Merge Sort Algorithm

Source: Author’s work.

Figure 30: Merge Parts method in Merge Sort Algorithm

Source: Author’s work. The code from the images above shows that the sorted half of the array is also obtained by previously merging 2 sorted parts into one half of the array and each part is also sorted by merging 2 smaller sorted parts and so on. Therefore, the original array is progressively divided and merged through recursive calling or merge sort algorithm until each part has a single element which itself is sorted and no further dividing and merging is required. Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

41

According to Toptal (2016), merge sort algorithm is extremely useful for sorting linked lists or in situations where random access is more expensive than sequential access, because of the stability and non-adaptiveness of the algorithm.

3.2.3 Performance Comparison of Simple Sorting with Divide and Conquer Sorting Algorithms Simple sorting algorithms such as insertion sort algorithms are much less efficient on large data sets because it sorts the array one entry at a time in a linear manner (Tang 2012). Even though insertion sorting algorithms are overall better than selection sort or bubble sort as mentioned previously, it still results in a logarithmic performance of just 0(n2) as revealed through the works of Mishra & Garg (2008). Therefore, its performance is lower than that of divide and conquer algorithms which boasts a performance of 0(1) and proves that divide and conquer algorithms are much more efficient than simple sorting algorithms, even as protruded by the vast calculations of the Raford University (2016).

3.3 Explain common string operations such as concatenation, substring, trim etc., also state their practical applications. (LO 3.1)

3.3.1 Sub-Strings A sub-string is a sequence of characters that contains in a string value. Substrings helps in separating a character or a set of characters apart from an existing string value thereby enabling to make a modified copy of the original text. The methods such as IndexOf, IndexOfAny, LastIndexOf, and LastIndexOfAny relies on substring techniques (Deitel & Deitel 2005). The following points shows how sub-strings could be achieved using the Substring method and its practical applications.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

42



Substring Method

The Substring method takes 2 arguments in integer format to identify where it should start the separation and where it should end. The Substring method does not accept the string itself as an argument, therefore the string object is required to perform the operation rather than the string text. The first 3 lines of code in figure 27 demonstrates the use of the Substring method in C# language. One practical application of this method is that certain phrases from a user’s input could be extracted to form a more relative output based on the input. 

Replace Method

The Replace method also accepts 2 arguments as parameters, it is required that the first argument to be the substring which should be replaced and the second argument to be the substring to be substituted with the first argument. Lines 4 to 6 in figure 27 illustrates the Replace method in use. This method is extremely useful where certain characters are required to be replaced such as in the case of making web URL’s more readable by replacing each forward slash with commas. 

IndexOf Method

The IndexOf method accepts just one argument where a character is passed in return for its index or position in the string, considering the string as an array of characters where white spaces are ignored. The last 3 lines of code in figure below shows the use of IndexOf method to return its index value. The substring method mentioned above requires the starting and ending index to be passed as arguments into the method. IndexOf method would therefore help in finding such indexes. For example, the figure below shows the method used to find the index of ‘C’ from the string s3.

Figure 31: Substring and related methods Source: Microsoft (2016).

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

43

3.3.2 Concatenation Concatenation is the process of merging two data literals into a single literal. Concatenation is not limited to string literals and could be used in any other data type such as binary, integer, floating point characters and Boolean. However, concatenation find its syntax to be different across languages (Techopedia 2016). The application of concatenation for string literals in the Java programming language is discussed below. Even in the Java programming language itself, there are various approaches for concatenation of string values. Each approach has their effects on performance and efficiency of the code. The easiest way to achieve concatenation of strings in java is to simply merge 2 strings using the operator ‘+’ as shown in the image below.

Figure 32: Concatenation using the '+' operator

Source: Author’s work. Even though the above approach for concatenation of strings is almost pleasant and readable, the practice of using ‘+’ operator for concatenation is highly discouraged by Nakov (2013), as the action would result in various performance issues due to reduced efficiency in the process involved while the operator is being used. As a possible solution to this problem, Kulandai (2015) suggests the use of buffered strings as it would significantly reduce the time taken to complete the concatenation process. In this approach, the append method is being used as seen through the image below.

Figure 33: Concatenation of strings by append method

Source: Author’s work.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

44

The above code sample shows string concatenation but with a string buffer in use where the actual result needs to be converted to a string again. However, there are alternative solutions that performs true concatenation yet without the need of string buffers. The concat method is such an approach where the string to be merged is passed as an argument into the method as shown through the image below.

Figure 34: Concatenation of strings through the concat method

Source: Tutorials Point (2016). The practical applications of concatenation include merging certain substrings which might have been extracted from the user into new string literals or in making new content from existing data such as the use of location names from maps to create readable addresses.

3.3.3 Trim Method The string trim method in java language is used to eliminate leading and trailing white spaces from a string. It uses the Unicode value of space which is ‘\u0020’ to check whether a given string contains such a Unicode at the beginning or the end, so this method cannot omit middle spaces in the string (Java T Point 2014). A possible use of this method includes validating user inputs where the user might have accidentally typed in white spaces at the beginning or the end of the input. In such a case, the absence of omission of middle spaces in the trim method comes as an advantage, because the input from the user is not altered while validating. The image below shows how this method is being used in the java language.

Figure 35:String Trim method in java

Source: Author’s work.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

45

Appendices Appendix A: Conclusion In the beginning of this document at Task 1, a program for figuring out whether certain strings are palindromes is developed. It uses many techniques and methods for string processing to process the input strings to validate them, for instance removal of white spaces and punctuation marks from the input string is practiced. This program uses an array based stack to reverse the string to check whether the reversed output matches the processed input. This method could be improved in the future where the array based stack could be replaced with a linked list. However, a program that uses a linked list is developed for the task 2 based scenario where the program enables processing of students in a waiting list in the form of a queue using queue operations such as enque and deque. As this is already a better implementation, this program only requires a better design such as a Graphical User Interface which would be more visually appealing than the current version which aides an Output Console from the IDE. It is clear from the many types of algorithms presented and explained through Task 3, that every algorithm is unique and is more efficient than others on certain tasks, scenarios or conditions. For example, even though insertion sorting algorithms are less efficient than merge sorting algorithms, for data sets below 10 – 12 elements in size, insertion sorting outperforms most of other types of algorithms available including merge sort. However, it is worth noting that on average, for most cases, the Divide and Conquer algorithms are more efficient and faster than Simple Sorting algorithms as they prove a more logarithmic performance. Therefore, the use of the correct type of data structure as well as the algorithm for the specific problem is always essential for implementing faster and efficient programs.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

46

Appendix B: Self-Reflection Though it took so long to catch up, Data Structures & Algorithms became an interesting area which helps in understanding how certain software work and behave. The different types of data structures, algorithms and multiple approaches for sorting and searching data found on this module reveals that the area studied is just the surface, and promotes the learning of much more sophisticated methods in the future. As a novice, it is always hard to understand how exactly modern software are supported using the techniques introduced in this module, however while completing this assignment, it became evident that there are vast amounts of research and experimental work dedicated for this area alone in which cases, the most efficient approaches, algorithms and methods are found and invented, specially based on their performance. However, it is a reason to worry, that such great research could not be referenced in this document. It is a pleasure to learn about strings and how they could be processed using different methods in a programming language. It is also a pleasure learning about algorithms and where exactly specific algorithms should be used. However, it was unclear and hard to understand about certain data structures such as Graphs and Trees, and how the algorithms are used to sort data in such forms. While it was confusing how certain coding practices and techniques differ the performance of algorithms, such as in the case of recursive and nonrecursive binary searching algorithms where the recursive always outperforms the iterative one, they were always promising a whole new perspective of observing the problem from which knowledge about how they actually work could be increased. These skills whether great or small would be beneficent in the future whether it would be for sorting data or for solving other problems as well. Therefore, this document would serve as a problem solver in the future as it could be used as a revision tool when the above mentioned weaknesses arrive.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

47

Appendix C: The Gantt Chart

Time Duration: 21 days [ 3 Weeks] Week 2

Week 3

01/09/16 02/09/16 03/09/16 04/09/16 05/09/16 06/09/16 07/09/16 08/09/16 09/09/16 10/09/16 11/09/16 12/09/16 13/09/16 14/09/16

31/08/16

Date

Week 1

15/09/16 16/09/16 17/09/16 18/09/16 19/09/16 20/09/16

Phases

Chapter 1 Chapter 2 Chapter 3 Finalization

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

48

References Abualrob, M. (2010) Iterative Binary search. Weblog. [Online] Available from: http://www.8bitavenue.com/2010/09/iterative-binary-search/ [Accessed 31st August 2016. GMT 11:25:27]. Beniwal, M., Singh, A., Diwan, A., Kaushik, J., Kumar, K.N., Singh, V., Gautam, N. & Joshi,

V.P.

(2016)

Insertion

sorting.

[Online]

http://www.studytonight.com/data-structures/insertion-sorting

Available

from:

31st

August

[Accessed

2016]. C Programming. (2011) Linear Search, Binary Search and other searching Techniques. [Online]

Available

from:

http://www.cprogramming.com/discussionarticles/sorting_and_searching.html

[Accessed

01st September 2016]. Cormen, T.H., Leiserson, C.E., Rivest, R.L. & Stein, C. (2009) Introduction to Algorithms, Third Edition. 3rd edition. [e-book] Massachusetts, MIT Press. Available from: https://mitpress.mit.edu/books/introduction-algorithms [Accessed 02nd September 2016]. Damier,

I.

(2015)

Iterative

Binary

Search.

[Online]

http://www.geekviewpoint.com/java/search/binary_search_iterative

Available

from:

[Accessed

03rd

September 2016]. Deitel, H.M. & Deitel, P. (2005) Strings, Characters and Regular Expressions. In: C# for Programmers. USA, Prentice Hall Professional, p. 616. Forrest, P. (2016) What is non-recursive binary search Algorithm? Weblog. [Online] Available

from:

http://www.answers.com/Q/What_is_non_recursive_binary_search_algorithm

[Accessed

04th September 2016. GMT 10:23:26]. Geeks

for

Geeks.

(2016)

Merge

Sort.

[Online]

Available

from:

http://quiz.geeksforgeeks.org/merge-sort/ [Accessed 05th September 2016]. Java

T

Point.

(2014)

Java

String

trim.

[Online]

Available

from:

http://www.javatpoint.com/java-string-trim [Accessed 6th September 2016]. Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

49

Knight, V. (2013) Comparing Recursive and Iterative Algorithms: Binary Search and Factorial.

Weblog.

[Online]

Available

from:

http://drvinceknight.blogspot.com/2013/06/im-in-middle-of-putting-together-new.html [Accessed 07th September 2016. GMT 09:15:37]. Kulandai, J. (2015) Java String Concatenation. Weblog. [Online] Available from: http://javapapers.com/core-java/java-string-concatenation/ [Accessed 08th September 2016. GMT 09:22:26]. Microsoft. (2016) Strings (C# Programming Guide). [Online] Available from: https://msdn.microsoft.com/en-us/library/ms228362(v=vs.100).aspx

[Accessed

09th

September 2016]. Mishra, A.D. & Garg, D. (2008) Selection of best Sorting Algorithm. International Journal of Intelligent Information Processing, 2 (2), 363 – 368. Nakov, S. (2013) Strings and Text processing In: Fundamentals of Computer programming with C#: The Bulgarian C# Book. Bulgaria, Svetlin Nakov, p. 484. Oracle Corporation (1997) PL/SQL User’s Guide and Reference Release 8.0. [Online] Available

from:

https://www.bnl.gov/phobos/Detectors/Computing/Orant/doc/database.804/a58236/06_err s.htm [Accessed 10th September 2016]. Raford University. (2016) Divide and Conquer Algorithms. [Online] Available from: http://www.radford.edu/~nokie/classes/360/divcon.html [Accessed 11th September 2016]. Rouse,

M.

(2007)

Error

Handling.

Weblog

[Online]

Available

http://searchsoftwarequality.techtarget.com/definition/error-handling

from:

[Accessed12th

September 2016. GMT 10:14:17]. Ruehr, F. (1998) Data Structures and Algorithms: Sorting Algorithms. Presented at Willamette

University.

Oregon.

[Online]

Available

from:

http://www.willamette.edu/~fruehr/dsa/lectures/sorting1.html [Accessed 13th September 2016].

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

50

Ryerson

University.

(2004)

Sorting

Algorithms.

[Online]

http://www.ee.ryerson.ca/~courses/coe428/sorting/insertionsort.html

Available

from:

[Accessed

14th

September 2016]. Stoimen. (2011) Computer Algorithms: Binary Search. Weblog. [Online] Available from: http://www.stoimen.com/blog/2011/12/26/computer-algorithms-binary-search/ [Accessed 15th September 2016. GMT 11:38:26]. Swartz, F. (2003) C++ Notes: Algorithms: Recursive Binary Search. [Online] Available from:

http://www.fredosaurus.com/notes-cpp/algorithms/searching/rbinarysearch.html

[Accessed 16th September 2016]. Tang, D. (2012) Introduction to Sorting Algorithms. [Online] Available from: https://www.cpp.edu/~ftang/courses/CS241/notes/sorting.htm [Accessed 17th September 2016]. Techopedia.

(2016)

Concatenation.

[Online]

Available

from:

https://www.techopedia.com/definition/3470/concatenation-programming [Accessed 18th September 2016]. Toptal.

(2016)

Merge

Sort.

[Online]

https://www.toptal.com/developers/sorting-algorithms/merge-sort

Available

from:

[Accessed

19th

September 2016]. Tripathi, P. (2014) Binary Search Implementation using C#. Weblog. [Online] Available from: http://www.c-sharpcorner.com/blogs/binary-search-implementation-using-c-sharp1 [Accessed 20th September 2016. GMT 08:22:23]. Tutorials Point. (2016) Java – String concat() Method. [Online] Available from: http://www.tutorialspoint.com/java/java_string_concat.htm

[Accessed 21st

September

2016].

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

51

Bibliography Bender, M.A., Colton, M.F. & Mosteiro, M.A. (2006) Insertion Sort is 0(n log n). Theory of Computing Systems, 39 (3), 391 – 397. Castro, V.E. & Wood, D. (1992) A Survey of Adaptive Sorting Algorithms. ACM Computing Surveys, 24 (4), 441 – 476. Cook, C.R. & Kim, D.J. (1980) Best sorting algorithm for nearly sorted Lists. Communications of the ACM, 23 (11), 620 – 624. Darlington, J. (1978) A Synthesis of several sorting Algorithms. Acta Informatica, 11 (1), 1 – 30. Department of Computer Science. (2015) Introduction to Data Structures. CS 46B. San Jose, San Jose State University. Franciszek, G. & Dominik, S. (2006) Dynamic Behavior of simple Insertion sort Algorithm. Fundamenta Informaticae, 72 (1), 155 – 165. Karunanithi, A.K. (2014) A Survey, Discussion and Comparison of Sorting algorithms. Master’s thesis. Umea University. Mcllroy, M.D. & Bentley, J.L. (1993) Engineering a sort function. Journal of Software: Practice and Experience, 23 (11), 1249 – 1265. Rajasekaran, S. (2001) A Framework for Simple Sorting Algorithms on Parallel Disk Systems. Theory of Computing Systems, 34 (2), 101 – 114. Samet, H. (1990) The Design and Analysis of Spatial Data Structures. USA, AddisonWesley. Sedgewick, R. (1978) Implementing Quicksort programs. Communications of the ACM. 21 (10), 847–857. Vazirani, U., Dasgupta, S. & Papadimitriou, C. (2006) Algorithms. 1st edition. New York, Mcgraw Hill Education.

Nilshan Devinda

REG: 7919

Data Structures & Algorithms

Unit 34

52

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF