This is my algorithm for Insertion Sort. It always skips the first element in the array.
Example:
Input:
5 8 4 9
Output:5 4 8 9
Here is the code.
import java.util.*;
class InsertionSort {
public void InsertAsc(int A [],int n)
{
for (int j=1; j<n; ++j){
int key=A[j];
int i=j-1;
while(i>0 &&A[i]>key)
{
A[i+1]=A[i];
i=i-1;
}
A[i+1]=key;
}
System.out.println("The sorted numbers are"+Arrays.toString(A));
}
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the numbers of number that you want to sort");
int n=scan.nextInt();
int A[]=new int[n];
System.out.println("Enter the numbers that you want to sort");
for(int i=0;i<n;i++)
{
A[i]=scan.nextInt();
}
System.out.println("The numbers are"+Arrays.toString(A));
InsertionSort ob = new InsertionSort();
ob.InsertAsc(A,n);
}
}
This is my algorithm for Insertion Sort. But it always skips the first element in the array.
Example:
Input:
5 8 4 9
Output:5 4 8 9
Here is the code.
import java.util.*;
class InsertionSort {
public void InsertAsc(int A [],int n)
{
for (int j=1; j<n; ++j){
int key=A[j];
int i=j-1;
while(i>0 &&A[i]>key)
{
A[i+1]=A[i];
i=i-1;
}
A[i+1]=key;
}
System.out.println("The sorted numbers are"+Arrays.toString(A));
}
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the numbers of number that you want to sort");
int n=scan.nextInt();
int A[]=new int[n];
System.out.println("Enter the numbers that you want to sort");
for(int i=0;i<n;i++)
{
A[i]=scan.nextInt();
}
System.out.println("The numbers are"+Arrays.toString(A));
InsertionSort ob = new InsertionSort();
ob.InsertAsc(A,n);
}
}
Thanks!
Pay close attention to this line while(i>0 &&A[i]>key) your variable i needs to go to index 0 as well and in your case it isn't so i>=0 fixes it.
Also I hope you can visualize how the algorithm is working-
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.