GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — java-coding-problems/InPlaceMergeSortedArray.java at main · GitH05/java-coding-problems

Expand file tree

/

InPlaceMergeSortedArray.java

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
49 lines (41 loc) · 1.46 KB
/

InPlaceMergeSortedArray.java

Copy path

File metadata and controls

49 lines (41 loc) · 1.46 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.Arrays;
class InPlaceMergeSortedArray
{
// Function to in-place merge two sorted arrays X[] and Y[]
// invariant: `X[]` and `Y[]` are sorted at any point
public static void merge(int[] X, int[] Y)
{
int m = X.length;
int n = Y.length;
// Consider each element `X[i]` of array `X` and ignore the element if it is
// already in the correct order; otherwise, swap it with the next smaller
// element, which happens to be the first element of `Y`.
for (int i = 0; i < m; i++)
{
// compare the current element of `X[]` with the first element of `Y[]`
if (X[i] > Y[0])
{
// swap `X[i]` with `Y[0]`
int temp = X[i];
X[i] = Y[0];
Y[0] = temp;
int first = Y[0];
// move `Y[0]` to its correct position to InPlaceMergeSortedArraytain the sorted
// order of `Y[]`. Note: `Y[1…n-1]` is already sorted
int k;
for (k = 1; k < n && Y[k] < first; k++) {
Y[k - 1] = Y[k];
}
Y[k - 1] = first;
}
}
}
public static void main(String[] args)
{
int[] X = { 1, 4, 7, 8, 10 };
int[] Y = { 2, 3, 9 };
merge(X, Y);
System.out.println("X: " + Arrays.toString(X));
System.out.println("Y: " + Arrays.toString(Y));
}
}
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.