Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Created by MOHIT on 01-10-2017.
- */
- // program to implement counting sort algorithm in java
- import java.util.Scanner;
- public class counting_sort {
- public static Scanner sc = new Scanner(System.in);
- public static void main(String arg[]){
- int[] myList;
- int length, element;
- System.out.println("Program to implement counting sort algorithm in C++");
- System.out.print("Enter the number of Elements to be sorted : ");
- length = sc.nextInt();
- myList = new int[length];
- System.out.println("Enter the elements to be sorted : ");
- for(int index = 0; index < length; index++){
- element = sc.nextInt();
- myList[index] = element;
- }
- int minElement = myList[0], maxElement = myList[0];
- for(int index = 0; index < length; index++){
- if(minElement > myList[index]){
- minElement = myList[index];
- }
- if(maxElement < myList[index]){
- maxElement = myList[index];
- }
- }
- System.out.println("The list of elements before sorting is : ");
- displayList(myList, length);
- myList = countingSort(myList, length, minElement, maxElement);
- System.out.println("The sorted list is : ");
- displayList(myList, length);
- }
- // function that prints list of elements
- static void displayList(int elementList[], int length){
- for(int index = 0; index < length; index++){
- System.out.print(elementList[index] + " ");
- }
- System.out.println("\n");
- }
- // function that sorts and returns the sorted list
- static int[] countingSort(int myList[], int length, int minElement, int maxElement){
- // finding the length, min, max of the recieved list of numbers
- int element;
- // creating a count list with initial values as zeros
- int[] countList = new int[maxElement - minElement + 1];
- for (int index = 0; index < (maxElement - minElement + 1); index++){
- countList[index] = 0;
- }
- // counting number of times each element occurs in the list and storing the count in the coutList
- for(int index = 0; index < length; index++) {
- element = myList[index];
- countList[element - minElement] = countList[element - minElement] + 1;
- }
- // starting from the min element upto max element
- // we insert values according to their count in the new list in sorted order
- element = minElement;
- int index2 = 0;
- for (int index = 0; index < (maxElement - minElement + 1); index++){
- int Count = countList[index];
- for(int j = 0; j < Count; j++) {
- myList[index2] = element;
- index2++;
- }
- element += 1;
- }
- return myList;
- }
- }
Add Comment
Please, Sign In to add comment