排序算法及其子算法

排序算法及其子算法

  • 各类排序算法
    • 插入排序(insertion sort)
    • 融合排序(Merge Sort)
      • merge two sorted array
    • 两个数组的交集Intersection of two array(leetcode)

各类排序算法

插入排序(insertion sort), 选择排序(selection sort),

插入排序(insertion sort)

public class InsertSort {
    public static void insertSort(int[] a) {
        int i, j, insertNote;// 要插入的数据
        for (i = 1; i < a.length; i++) {// 从数组的第二个元素开始循环将数组中的元素插入
            insertNote = a[i];// 设置数组中的第2个元素为第一次循环要插入的数据
            j = i - 1;
            while (j >= 0 && insertNote < a[j]) {
                a[j + 1] = a[j];// 如果要插入的元素小于第j个元素,就将第j个元素向后移动
                j--;
            }
            a[j + 1] = insertNote;// 直到要插入的元素不小于第j个元素,将insertNote插入到数组中
        }
    }

    public static void main(String[] args) {
        int a[] = { 38,65,97,76,13,27,49 };
        insertSort(a);
        System.out.println(Arrays.toString(a));
    }
}

融合排序(Merge Sort)

merge two sorted array

  • Time Complexity : O ( n 1 + n 2 ) O(n1 + n2) O(n1+n2) (linear time)
  • Auxiliary Space : O ( n 1 + n 2 ) O(n1 + n2) O(n1+n2) (not in-place)
// Java program to merge two sorted arrays 
import java.util.*; 
import java.lang.*; 
import java.io.*; 

class MergeTwoSorted 
{ 
	// Merge arr1[0..n1-1] and arr2[0..n2-1] 
	// into arr3[0..n1+n2-1] 
	public static void mergeArrays(int[] arr1, int[] arr2, int n1, 
								int n2, int[] arr3) 
	{ 
		int i = 0, j = 0, k = 0; 
	
		// Traverse both array 
		while (i<n1 && j <n2) 
		{ 
			// Check if current element of first 
			// array is smaller than current element 
			// of second array. If yes, store first 
			// array element and increment first array 
			// index. Otherwise do same with second array 
			if (arr1[i] <= arr2[j])  //这里<=可以保证用于merge sort的时候是stable的,原来顺序不变
				arr3[k++] = arr1[i++]; 
			else
				arr3[k++] = arr2[j++]; 
		} 
	
		// Store remaining elements of first array 
		while (i < n1) 
			arr3[k++] = arr1[i++]; 
	
		// Store remaining elements of second array 
		while (j < n2) 
			arr3[k++] = arr2[j++]; 
	} 
	
	public static void main (String[] args) 
	{ 
		int[] arr1 = {1, 3, 5, 7}; 
		int n1 = arr1.length; 
	
		int[] arr2 = {2, 4, 6, 8}; 
		int n2 = arr2.length; 
	
		int[] arr3 = new int[n1+n2]; 
		
		mergeArrays(arr1, arr2, n1, n2, arr3); 
	
		System.out.println("Array after merging"); 
		for (int i=0; i < n1+n2; i++) 
			System.out.print(arr3[i] + " "); 
	} 
} 

两个数组的交集Intersection of two array(leetcode)

LeetCode 原链接

  • Use two hash sets, Time complexity: O ( n ) O(n) O(n)
public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<>();
        Set<Integer> intersect = new HashSet<>();
        for (int i = 0; i < nums1.length; i++) {
            set.add(nums1[i]);
        }
        for (int i = 0; i < nums2.length; i++) {
            if (set.contains(nums2[i])) {
                intersect.add(nums2[i]);
            }
        }
        int[] result = new int[intersect.size()];
        int i = 0;
        for (Integer num : intersect) {
            result[i++] = num;
        }
        return result;
    }
}
  • Sort both arrays, use two pointers, Time complexity: O ( n l o g n ) O(nlogn) O(nlogn)
    这个 O ( n l o g n ) O(nlogn) O(nlogn)是因为排序算法导致的. 如果单考虑intersection的部分,应该是 O ( m + n ) O(m+n) O(m+n)
public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<>();
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i = 0;
        int j = 0;
        while (i < nums1.length && j < nums2.length) {
            if (nums1[i] < nums2[j]) {
                i++;
            } else if (nums1[i] > nums2[j]) {
                j++;
            } else {
                set.add(nums1[i]);
                i++;
                j++;
            }
        }
        int[] result = new int[set.size()];
        int k = 0;
        for (Integer num : set) {
            result[k++] = num;
        }
        return result;
    }
}
  • Binary search, Time complexity: O ( n l o g n ) O(nlogn) O(nlogn)
public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<>();
        Arrays.sort(nums2);
        for (Integer num : nums1) {
            if (binarySearch(nums2, num)) {
                set.add(num);
            }
        }
        int i = 0;
        int[] result = new int[set.size()];
        for (Integer num : set) {
            result[i++] = num;
        }
        return result;
    }
    
    public boolean binarySearch(int[] nums, int target) {
        int low = 0;
        int high = nums.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (nums[mid] == target) {
                return true;
            }
            if (nums[mid] > target) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return false;
    }
}

你可能感兴趣的:(Algorithm)