You are on page 1of 12

INTRODUCTION:

SORTING
is any process of arranging items in some sequence and/or in different sets, and accordingly, it has two common, yet distinct meanings: ordering: arranging items of the same kind, class, nature, etc. in some ordered sequence, categorizing: grouping and labeling items with similar properties together (by sorts). When computer programmers write a program, many of the things that they do can be reduced to basic algorithms that can be applied to other similar problems. For example, you can apply the same technique to sorting a list of names that you used for sorting a list of birthdays. In fact, you can use it for sorting any set of objects with a natural ordering. Sorting a series of objects is a very common objective, one that many programs need to implement a solution for. - In computer science, 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 for 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: The output is in nondecreasing order (each element is no smaller than the previous element according to the desired total order); The output is a permutation, or reordering, of the input. Since the dawn of computing, the sorting problem has attracted a great deal of research, perhaps due to the complexity of solving it efficiently despite its simple, familiar statement. For example,bubble sort was analyzed as early as 1956.[1] Although many consider it a solved problem, useful new sorting algorithms are still being invented (for example, library sort was first published in 2004). Sorting algorithms are prevalent in introductory computer science classes, where the abundance of algorithms for the problem provides a gentle introduction to a variety of core algorithm concepts, such as big O notation, divide and conquer algorithms, data structures, randomized algorithms, best, worst and average case analysis, time-space tradeoffs, and lower bounds.

SORTING TECHNIQUES

Bubble Sort
Bubble sort is a simple and well-known sorting algorithm. It is used in practice once in a blue moon and its main application is to make an introduction to the sorting algorithms. Bubble sort belongs to O(n 2) sorting algorithms, which makes it quite inefficient for sorting large data volumes. Bubble sort is stable and adaptive.

Algorithm
1. Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them. 2. If at least one swap has been done, repeat step 1. You can imagine that on every step big bubbles float to the surface and stay there. At the step, when no bubble moves, sorting stops. Let us see an example of sorting an array to make the idea of bubble sort clearer.

Code snippets
There are several ways to implement the bubble sort. Notice, that "swaps" check is absolutely necessary, in order to preserve adaptive property.
Java
public void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } }

REFERENCE: http://www.algolist.net/Algorithms/Sorting/Bubble_sort

Insertion sort.
Insertion sort is a brute-force sorting algorithm that is based on a simple method that people often use to arrange hands of playing cards. Consider the cards one at a time and insert each into its proper place among those already considered (keeping them sorted). The following code mimics this process in a Java method that sorts strings in an array: public static void sort(String[] a) { int N = a.length; for (int i = 1; i < N; i++) for (int j = i; j > 0; j--) if (a[j-1].compareTo(a[j]) > 0) exch(a, j, j-1); else break; } The outer for loop sorts the first i entries in the array; the inner for loop can complete the sort by putting a[i] into its proper position in the array.

Mathematical analysis. The inner loop of the insertion sort code is within a double for loop, which suggests that the running time is quadratic, but we cannot immediately draw this conclusion because of the break. o Best case. When the input array is already in sorted order, the inner for loop amounts to nothing more than a comparison (to learn thata[j-1] is less than a[j]) and the break, so the total running time is linear. o Worst case. When the input is reverse sorted, the inner loop fully completes without a break, so the frequency of execution of the instructions in the inner loop is 1 + 2 + ... + N-1 ~ N^2 and the running time is quadratic. o Average case. When the input is randomly ordered To understand the performance of insertion sort for randomly ordered, we expect that each new element to be inserted is equally likely to fall into any position, so that element

will move halfway to the left on average. Thus, we expect the running time to be 1/2 + 2/2 + ... + (N-1)/2 ~ N^2 / 2. Sorting other types of data. We want to be able to sort all types of data, not just strings. For sorting objects in an array, we need only assume that we can compare two elements to see whether the first is bigger than, smaller than, or equal to the second. Java provides the Comparableinterface for precisely this purpose. Simply put, a class that implements the Comparable interface promises to implement a method compareTo()for objects of its type so that that a.compareTo(b) returns a negative integer if a is less than b, a positive integer if a is greater than b, and 0 if a is equal to b. The precise meanings of less than, greater than, and equal to are up to the data type, though implementations that do not respect the natural laws of mathematics surrounding these concepts will yield unpredictable results. With this convention, Insertion.java implements insertion sort so that it sorts arrays of Comparable objects. Empirical analysis. Program InsertionTest.java tests our hypothesis that insertion sort is quadratic for randomly ordered files. It relies on the helper data type Stopwatch.java. Sensitivity to input. Note that InsertionTest.java takes a command-line parameter M and runs M experiments for each array size, not just one. One reason for doing so is that the running time of insertion sort is sensitive to its input values. It is not correct to flatly predict that the running time of insertion sort will be quadratic, because your application might involve input for which the running time is linear.

REFERENCE : http://www.algolist.net/Algorithms/Sorting/Insertion_sort

Selection Sort
Selection sort is one of the O(n 2) sorting algorithms, which makes it quite inefficient for sorting large data volumes. Selection sort is notable for its programming simplicity and it can over perform other sorts in certain situations (see complexity analysis for more details).

Algorithm
The idea of algorithm is quite simple. Array is imaginary divided into two parts sorted one and unsorted one. At the beginning, sorted part is empty, while unsorted one contains whole array. At every step, algorithm finds minimal element in the unsorted part and adds it to the end of the sorted one. When unsorted part becomes empty, algorithmstops. When algorithm sorts an array, it swaps first element of unsorted part with minimal element and then it is included to the sorted part. This implementation of selection sort in not stable. In case of linked list is sorted, and, instead of swaps, minimal element is linked to the unsorted part, selection sort is stable.

Code snippets
Java
public int int for void selectionSort(int[] arr) {

i, j, minIndex, tmp; n = arr.length; (i = 0; i < n - 1; i++) { minIndex = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[minIndex]) minIndex = j; if (minIndex != i) { tmp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = tmp; }

} } REFERENCE : http://www.algolist.net/Algorithms/Sorting/Selection_sort

Quicksort
Quicksort is a fast sorting algorithm, which is used not only for educational purposes, but widely applied in practice. On the average, it has O(n log n) complexity, making quicksort suitable for sorting big data volumes. The idea of the algorithm is quite simple and once you realize it, you can write quicksort as fast as bubble sort.

Algorithm
The divide-and-conquer strategy is used in quicksort. Below the recursion step is described: Choose a pivot value. We take the value of the middle element as pivot value, but it can be any value, which is in range of sorted values, even if it doesn't present in the array. 2. Partition. Rearrange elements in such a way, that all elements which are lesser than the pivot go to the left part of the array and all elements greater than the pivot, go to the right part of the array. Values equal to the pivot can stay in any part of the array. Notice, that array may be divided in non-equal parts. 3. Sort both parts. Apply quicksort algorithm recursively to the left and the right parts.
1.

Code snippets
Partition algorithm is important per se, therefore it may be carried out as a separate function. The code for C++ contains solid function for quicksort, but Java code contains two separate functions for partition and sort, accordingly.
Java
int partition(int arr[], int left, int right) { int i = left, j = right; int tmp; int pivot = arr[(left + right) / 2]; while (i <= j) { while (arr[i] < pivot) i++; while (arr[j] > pivot) j--; if (i <= j) { tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; } }; return i; } void quickSort(int arr[], int left, int right) { int index = partition(arr, left, right); if (left < index - 1) quickSort(arr, left, index - 1); if (index < right) quickSort(arr, index, right); }

REFERENCE : http://www.algolist.net/Algorithms/Sorting/Quicksort

Mergesort.
To develop a faster sorting method, we use a divide-and-conquer approach to algorithm design that every programmer needs to understand. This nomenclature refers to the idea that one way to solve a problem is to divide it into independent parts, conquer them independently, and then use the solutions for the parts to develop a solution for the full problem. To sort an array with this strategy, we divide it into two halves, sort the two halves independently, and then merge the results to sort the full array. This method is known as mergesort. To sort a[lo, hi), we use the following recursive strategy: base case: If the subarray size is 0 or 1, it is already sorted. recursive step: Otherwise, compute m = lo + (hi - lo)/2, sort (recursively) the two subarrays a[lo, m) and a[m, hi), and merge them to produce a sorted result.

Merge.java is an implementation. As usual, the easiest way to understand the merge process is to study a trace of the contents of the array during the merge.

Mathematical analysis. The inner loop of mergesort is centered on the auxiliary array. The two for loops involve N iterations (and creating the array takes time proportional to N), so the frequency of execution of the instructions in the inner loop is proportional to the sum of the subarray sizes for all calls to the recursive function. The value of this

quantity emerges when we arrange the calls on levels according to their size. On the first level, we have 1 call for size N, on the second level, we have 2 calls for size N/2, on the third level, we have 4 calls for size N/4, and so forth, down to the last level with N/2 calls of size 2. There are precisely lg N levels, giving the grand total N lg N for the frequency of execution of the instructions in the inner loop of mergesort. This equation justifies a hypothesis that the running time of mergesort is linearithmic.

Quadratic-linearithmic chasm. The difference between N^2 and N lg N makes a huge difference in practical applications. Understanding the enormousness of this difference is another critical step to understanding the importance of the design and analysis of algorithms. For a great many important computational problems, a speedup from quadratic to linearithmic makes the difference between being able to solve a problem involving a huge amount of data and not being able to effectively address it at all. Divide-and-conquer algorithms. The same basic approach is effective for many important problems, as you will learn if you take a course on algorithm design. Reduction to sorting. A problem A reduces to a problem B if we can use a solution to B to solve A. Designing a new divide-and-conquer algorithm from scratch is sometimes akin to solving a puzzle that requires some experience and ingenuity, so you may not feel confident that you can do so at first. But it is often the case that a simpler approach is effective: given a new problem that lends itself to a quadratic brute-force solution, ask yourself how you would solve it if the data were sorted in some way. For example, consider the problem of determining whether the elements in an array are all different. This problem reduces to sorting because we can sort the array, the make a linear pass through the sorted array to check whether any entry is equal to the next (if not, the elements are all different.)

Frequency counts. FrequencyCount.java reads a sequence of strings from standard input and then prints a table of the distinct values found and the number of times each was found, in decreasing order of the frequencies. We accomplish this by two sorts. Computing the frequencies. Our first step is to sort the strings on standard input. In this case, we are not so much interested in the fact that the strings are put into sorted order, but in the fact that sorting brings equal strings together. If the input is

to be or not to be to then the result of the sort is be be not or to to to with equal strings like the three occurrences of to brought together in the array. Now, with equal strings all together in the array, we can make a single pass through the array to compute all the frequencies. The Counter.java data type that we considered in Section 3.x is the perfect tool for the job.

Sorting the frequencies. Next, we sort the Counter objects. We can do so in client code without any special arrangements because Counterimplements the Comparable interface. Zipf's law. The application highlighted in FrequencyCount is elementary linguistic analysis: which words appear most frequently in a text? A phenomenon known as Zipf's law says that the frequency of the ith most frequent word in a text of M distinct words is proportional to 1/i.

Longest repeated substring. Another important computational task that reduces to sorting is the problem of finding the longest repeated substringin a given string. This problem is simple to state and has many important applications, including computer-assisted music analysis, cryptography, and data compression. Think briefly about how you might solve it. Could you find the longest repeated substring in a string that has millions of characters? Program LRS.java is a clever solution that uses suffix sorting.

REFERENCE : http://www.sorting-algorithms.com/merge-sort http://www.roseindia.net/java/beginners/arrayexamples/mergeSort.shtml

PROGRAM BUBBLE SORT :


import java.util.Scanner; public class Average{ public static int getAverage (String [] args){ Scanner gosh=new Scanner (System.in); int num [] = new int [10]; int sum = 0; for (int x = 0; x<10;x++){ System.out.println("Enter a number :"); num[x]=gosh.nextInt(); double average =0; } for (int x = 0;x<10; x++){ sum = num [x]; int average = sum/10; } int average = sum/10; System.out.println ("Average is equal to : " + average); int maximum = 0; int minimum = 0; for (int x = 0; x < 10; x ++){ if (num [x] > maximum){ maximum = num [x]; } else if (num [x] < minimum){ System.out.println ("maximum is equal to :" + maximum); System.out.println ("maximum is equal to :" + minimum); } public void sort(int [] arr){ boolean swapped = true; number = 0; int weee; while (swapped){ number++; for (int eeest = 0; eeest < arr.length-number; eeest++){ if (arr [eeest]>arr[eeest+1]){ weee = arr [eeest]; arr [eeest] = arr [ eeest + 1]; arr [eeest + 1] = weee; swapped = true; System.out.print (eeest); }

} } } } } }

You might also like