import java.util.*; classGFG { // Function to sort an array using insertion sort staticvoidinsertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1;
// Move elements of arr[0..i-1], // that are greater than key to // one position ahead of their // current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } }
// Function to print an array of size N staticvoidprintArray(int arr[], int n) { int i;
// Print the array for (i = 0; i < n; i++) { System.out.print(arr[i] + " "); } System.out.println(); }
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ classSolution { public ListNode insertionSortList(ListNode head) { //base case: if (head == null) return head; // loop invariants: // for each i in [0, n], list before head[i] is sorted, after is not sorted. // initialization: i = 1, becasue head[0] is already sorted by itself // maintenance: as i++, we need to insert head[i] into it's right place. // temination condition: when it passes all the elements ListNodelocal= head.next; intlocalTraverseCount=1; ListNodelocalPrev= head; ListNodeheadCopy= head; while(local != null) { // break current node localPrev.next = local.next; ListNodenext= local.next; // if it's the smallest if (local.val < headCopy.val) { local.next = headCopy; headCopy = local; } else { // loop through the first part to insert the node ListNodeinsertTraverse= headCopy; intinsertTraverseCount=1; //local invariants: insertTraverse.val is smaller than local.val but insertTraverse.next.val is bigger while (insertTraverseCount < localTraverseCount && insertTraverse.val < local.val && insertTraverse.next.val < local.val) { insertTraverse = insertTraverse.next; insertTraverseCount++; } // termination: it's own place, or found a node whose .next.val is bigger // insert local after insertTraverse ListNodetemp= insertTraverse.next; insertTraverse.next = local; local.next = temp; if (insertTraverseCount == localTraverseCount) { localPrev = local; } } localTraverseCount++; local = next; } return headCopy; } }
// To sort in descending order, change > to < in this line. // Select the minimum element in each loop. if (array[i] < array[min_idx]) { min_idx = i; } }
// put min at the correct position swap(array, min_idx, step); } }
// Java program to sort an // array using stack import java.io.*; import java.util.*;
classGFG { // This function return the sorted stack static Stack<Integer> sortStack(Stack<Integer> input) { Stack<Integer> tmpStack = newStack<Integer>(); while (!input.empty()) { // pop out the first element inttmp= input.peek(); input.pop(); // while temporary stack is not empty and top of stack is smaller than temp while (!tmpStack.empty() && tmpStack.peek() < tmp) { // pop from temporary stack and push it to the input stack input.push(tmpStack.peek()); tmpStack.pop(); } // push tmp in temporary of stack tmpStack.push(tmp); } return tmpStack; } staticvoidsortArrayUsingStacks(int []arr, int n) { // push array elements // to stack Stack<Integer> input = newStack<Integer>(); for (inti=0; i < n; i++) input.push(arr[i]); // Sort the temporary stack Stack<Integer> tmpStack = sortStack(input); // Put stack elements in arr[] for (inti=0; i < n; i++) { arr[i] = tmpStack.peek(); tmpStack.pop(); } } // Driver Code publicstaticvoidmain(String args[]) { int []arr = {10, 5, 15, 45}; intn= arr.length; sortArrayUsingStacks(arr, n); for (inti=0; i < n; i++) System.out.print(arr[i] + " "); } }
/* Java program for Merge Sort */ classMergeSort { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] voidmerge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged intn1= m - l + 1; intn2= r - m;
/* Create temp arrays */ int L[] = newint[n1]; int R[] = newint[n2];
/*Copy data to temp arrays*/ for (inti=0; i < n1; ++i) L[i] = arr[l + i]; for (intj=0; j < n2; ++j) R[j] = arr[m + 1 + j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays inti=0, j = 0;
// Initial index of merged subarray array intk= l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; }
/* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; }
/* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } }
// Main function that sorts arr[l..r] using // merge() voidsort(int arr[], int l, int r) { if (l < r) { // Find the middle point intm=l+ (r-l)/2;
// Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r);
// Merge the sorted halves merge(arr, l, m, r); } }
/* A utility function to print array of size n */ staticvoidprintArray(int arr[]) { intn= arr.length; for (inti=0; i < n; ++i) System.out.print(arr[i] + " "); System.out.println(); }
in order not to override, it’s best to move from right to left. so the condition need to check which bigger instead of who’s smaller
my first thought was moving all the elements of nums1 to the end and go from left. it works too, but there’s more to write.
how to write the condition is worth memorizing
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicvoidmerge(int[] nums1, int m, int[] nums2, int n) { intp= m - 1; intq= n - 1; for (inti= m + n - 1; i >= 0; i--) { // positive condition: when will we need to // swap with nums1 // 1. when nums1 still has elements and nums2 is out // 2. when nums1 still has elements and nums1[p] > nums2[q] // notes: it's ">" because we go from right to left. if (p >= 0 && (q < 0 || (nums1[p] > nums2[q]))) { nums1[i] = nums1[p--]; continue; } nums1[i] = nums2[q--]; } }