Answers for "insertion sort working"

7

insertion sort java

Insertion program
public class InsertionSortExample
{
   public void sort(int[] arrNum)
   {
      int number = arrNum.length;
      for(int a = 1; a < number; ++a)
      {
         int keyValue = arrNum[a];
         int b = a - 1;
         while(b >= 0 && arrNum[b] > keyValue)
         {
            arrNum[b + 1] = arrNum[b];
            b = b - 1;
         }
         arrNum[b + 1] = keyValue;
      }
   }
   static void displayArray(int[] arrNum)
   {
      int num = arrNum.length;
      for(int a = 0; a < num; ++a)
      {
         System.out.print(arrNum[a] + " ");
      }
      System.out.println();
   }
   public static void main(String[] args)
   {
      int[] arrInput = { 50, 80, 10, 30, 90, 60 };
      InsertionSortExample obj = new InsertionSortExample();
      obj.sort(arrInput);
      displayArray(arrInput);
   }
}
Posted by: Guest on October-23-2020
10

insertion sort

#insertion sort
def insert(arr):
    for i in range(1,len(arr)):
        while arr[i-1] > arr[i] and i > 0:
            arr[i], arr[i-1] = arr[i-1], arr[i]
            i -= 1 
    return arr 
arr = [23, 55, 12, 99, 66, 33]
print(insert(arr))
Posted by: Guest on July-24-2021
0

Insertion Sort

class Sort  
{ 
    static void insertionSort(int arr[], int n) 
    { 
        if (n <= 1)                             //passes are done
        {
            return; 
        }

        insertionSort( arr, n-1 );        //one element sorted, sort the remaining array
       
        int last = arr[n-1];                        //last element of the array
        int j = n-2;                                //correct index of last element of the array
       
        while (j >= 0 && arr[j] > last)                 //find the correct index of the last element
        { 
            arr[j+1] = arr[j];                          //shift section of sorted elements upwards by one element if correct index isn't found
            j--; 
        } 
        arr[j+1] = last;                            //set the last element at its correct index
    } 

    void display(int arr[])                 //display the array
    {  
        for (int i=0; i<arr.length; ++i) 
        {
            System.out.print(arr[i]+" ");
        } 
    } 
 
       
    public static void main(String[] args) 
    { 
        int arr[] = {22, 21, 11, 15, 16}; 
       
        insertionSort(arr, arr.length); 
        Sort ob = new Sort();
        ob.display(arr); 
    } 
}
Posted by: Guest on May-31-2021

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language