Skip to content

hardw0607/Countingsort-Java

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

Countingsort-Java

Countingsort Java public class countingsort {

public static void countingsort1(int arr[]) {
    int largest = Integer.MIN_VALUE;

    // Step 1: Find the largest element
    for (int i = 0; i < arr.length; i++) {
        largest = Math.max(largest, arr[i]);
    }

    // Step 2: Create count array
    int count[] = new int[largest + 1];

    // Step 3: Count occurrences
    for (int i = 0; i < arr.length; i++) {
        count[arr[i]]++;
    }

    // Step 4: Rebuild sorted array
    int j = 0;
    for (int i = 0; i < count.length; i++) {
        while (count[i] > 0) {
            arr[j] = i;
            j++;
            count[i]--;
        }
    }
}

//  Add this method to print the array
public static void printArr(int[] arr) {
    for (int num : arr) {
        System.out.print(num + " ");
    }
    System.out.println(); // for clean output
}

public static void main(String[] args) {
    int arr[] = {5, 4, 1, 3, 2};
    countingsort1(arr);
    printArr(arr); //  Now this works
}

} //chceck out the output //1 2 3 4 5

About

Countingsort Java

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published