|
| 1 | + |
| 2 | +importjava.util.Random; |
| 3 | + |
| 4 | +publicclassBucket_Sort |
| 5 | +{ |
| 6 | +staticint[]sort(int[]sequence,intmaxValue) |
| 7 | + { |
| 8 | +// Bucket Sort |
| 9 | +int[]Bucket =newint[maxValue +1]; |
| 10 | +int[]sorted_sequence =newint[sequence.length]; |
| 11 | + |
| 12 | +for (inti =0;i <sequence.length;i++) |
| 13 | +Bucket[sequence[i]]++; |
| 14 | + |
| 15 | +intoutPos =0; |
| 16 | +for (inti =0;i <Bucket.length;i++) |
| 17 | +for (intj =0;j <Bucket[i];j++) |
| 18 | +sorted_sequence[outPos++] =i; |
| 19 | + |
| 20 | +returnsorted_sequence; |
| 21 | + } |
| 22 | + |
| 23 | +staticvoidprintSequence(int[]sorted_sequence) |
| 24 | + { |
| 25 | +for (inti =0;i <sorted_sequence.length;i++) |
| 26 | +System.out.print(sorted_sequence[i] +" "); |
| 27 | + } |
| 28 | + |
| 29 | +staticintmaxValue(int[]sequence) |
| 30 | + { |
| 31 | +intmaxValue =0; |
| 32 | +for (inti =0;i <sequence.length;i++) |
| 33 | +if (sequence[i] >maxValue) |
| 34 | +maxValue =sequence[i]; |
| 35 | +returnmaxValue; |
| 36 | + } |
| 37 | + |
| 38 | +publicstaticvoidmain(Stringargs[]) |
| 39 | + { |
| 40 | +System.out.println("Sorting of randomly generated numbers using BUCKET SORT"); |
| 41 | +Randomrandom =newRandom(); |
| 42 | +intN =20; |
| 43 | +int[]sequence =newint[N]; |
| 44 | + |
| 45 | +for (inti =0;i <N;i++) |
| 46 | +sequence[i] =Math.abs(random.nextInt(100)); |
| 47 | + |
| 48 | +intmaxValue =maxValue(sequence); |
| 49 | + |
| 50 | +System.out.println("\nOriginal Sequence: "); |
| 51 | +printSequence(sequence); |
| 52 | + |
| 53 | +System.out.println("\nSorted Sequence: "); |
| 54 | +printSequence(sort(sequence,maxValue)); |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +#Output: |
| 59 | + |
| 60 | +$javacBucket_Sort.java |
| 61 | +$javaBucket_Sort |
| 62 | + |
| 63 | +SortingofrandomlygeneratednumbersusingBUCKETSORT |
| 64 | + |
| 65 | +OriginalSequence: |
| 66 | +9599587881185457539215382485629696466 |
| 67 | +SortedSequence: |
| 68 | +8891518242938535456576466698187929595 |