'Why is this insertion sort code of java throwing exception
The question was to sort the digits of a number in ascending order using insertion sort. this code of mine throws exception at the arr[i] = num %10; line..
import java.util.Scanner;
public class Insertion_sort {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int count;
int temp = num;
public void counting() {
while (temp > 0) {
temp= temp / 10;
count++;
}
}
int []arr = new int[count];
public void solutions() {
for (int i = 0; i < count; i++) {
arr[i] = num % 10;
num = num / 10;
}
for (int i = 1; i < count; i++) {
int var = arr[i];
int j = i;
while (j > 0 && arr[j - 1] > var) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = var;
}
for (int i= 0; i< count; i++) {
System.out.println(arr[i]);
}
}
public static void main(String[] args) {
Insertion_sort obj = new Insertion_sort();
obj.solutions();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
