[Java] Arrays and Bubble Sort

· Tech· Java
Java

Array application example - Inserting a comma (,) every thousand in an integer


1.

In Java, you can use DecimalFormat to display a comma for every thousand. You can also create a DecimalFormat object and write #, ### notation. 

DecimalFormat df = new DecimalFormat("#,###");

String smoney = df.format(money);

System.out.println(smoney);

2.

The second method is to use an array.  Although it is more complicated than the method above, you can use two arrays to express , . First, create an input array and an array with , input. And if you think about the rules for notating thousands, you can see that , is written every four digits from the back. In other words, using a loop statement, the existing input array is substituted with and from the back.

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
50
51
52
53
54
55
56
package my.day09.b.array;
 
import java.text.DecimalFormat;
import java.util.Scanner;
 
public class MoneyCommaMain3 {
 
    public static void main(String[] args) {
        
        System.out.print("▷ 금액을 입력하세요(정수로만) => ");
        Scanner sc = new Scanner(System.in);
        long money = Long.parseLong(sc.nextLine());
        
        DecimalFormat df = new DecimalFormat("#,###");
        String smoney = df.format(money);
        System.out.println(smoney);
        
        System.out.println("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
        
        System.out.print("▶ 금액을 입력하세요(정수로만) => ");
        String inputStr = sc.nextLine();
        int len = inputStr.length();   // 입력받은 문자열의 길이
        int commaCount  = len/3;
        commaCount = (len%3= =0)?commaCount-1:commaCount;
        
        /*
             if(len%3==0) commaCount-=1;        // 같은 표현
            
            ----------------------------------------------------------
            |1|2|3|4|5|6|7|8|9|  →   |1|2|3|,|4|5|6|,|7|8|9|
            ---------------------------------------------
         */
        
        char[] moneyArr = inputStr.toCharArray();
        char[] outputArr = @@T413@ @new char[len+commaCount];
        
        ,@@@@@
        int cnt = 0// 반복횟수
        
        for (int i=outputArr.length@@T452@ @-1,j=moneyArr.length-@@T46 5@@1; 2@@=0;  i@@T479 @@--,j@@T486@ @--) {
            cnt++;
            if(cnt%4!=0) {
                outputArr[i]=moneyArr[j];
            } else {
                outputArr[i]=',';
                j++;
            }
        }
        
        System.out.println(outputArr);
        
        sc.close();
    }
 
}
 
cs

 

버블정렬


버블정렬은 배열을 수평 나열했다고 가정했을 때, 왼쪽 끝에서 옆 데이터 값과 비교하여 오름 또는 내림차순으로 재배치하는 것을 말한다.  인접 값을 비교를 통해 마지막 값이 제일 크거나 작은 수가 될 때까지 반복한다. 자바에서는 간단히 Arrays.sort(배열명) 으로 오름차순 정렬이 가능하다.

하지만, 아래와 같이 다중 for문으로 버블정렬의 효과를 나타낼 수도 있다.

 

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package my.day10.c.array;
import java.util.Arrays;
public class BubbleSortMain {
/*
== Employment issues ==
>> Bubble Sort is
Assuming that the items in the sort target list (array) are arranged horizontally,
Starting from the left end, compare the values of two adjacent items to
If it is not in the correct order (ascending or descending order), this is a sorting method that exchanges positions.
· The process of exchanging positions by comparing the values of adjacent items is:
Repeat until the last item in the list (array) so that the largest (or smallest) value is at the end.
At the end of each rotation (pass), sorting is completed one by one from the back. 
*/
public static void main(String[] args) {
int[] numArr = {@@T989 @@9,7,3,5,1}; 
/*
numArr[0] => 9
numArr[1] => 7
numArr[2] => 3
numArr[3] => 5
numArr[1] => 1
· */
        
      System.out.println("=== 정렬하기 전 ===");
      for(int i=0; i<numArr.length; i++) {
         String str = (i<numArr.length-1)?",":"\n";
         System.out.print(numArr[i]+str);
      }// end of for---------------------
      /*
         === 정렬하기 전 ===
          9,7,3,5,1 
          
                    --------------------
                  데이터값  => | 7 | 3 | 9 | 5 | 1 | 
-------------------- --
*/
       // === Sort in ascending order === //
       for(int i =0; i<nu mArr.length-1; i@@T1154@ @++) {
            // Number of objects to be compared to be extracted ==> How many are 9, 7, 3, 5? 4
        // (int i=0; i<4; i++)   
          for(int j@@T11 78@@=0; j<numArr.@@T1186 @@length-1-i; j@@T1194@ @++) { // i=0;  ==> Conditional expression j<4; 되어야만 4번 비교함.  
// i=1;  ==> Conditional expression j<3; 되어야만 3번 비교함.
// i=2;  ==> Conditional expression j<2; 되어야만 2번 비교함.
// i=3;  ==> Conditional expression j<1; 되어야만 1번 비교함.
            
| 1225@@ numArr[j+1]) {
// numArr[0] > numArr[1]
// 9 7
|
int temp = numArr[0];  // 9;
               numArr[0] = numArr[1]; // numArr[0] <= 7; 
               numArr[1] = temp;      // numArr[1] <= 9
               
               int temp = numArr[1];  // 9;
               numArr[1] = numArr[2]; // numArr[1] <= 3; 
               numArr[2] = temp;      // numArr[2] <= 9
               
               int temp = numArr[2];  // 9;
               numArr[2] = numArr[3]; // numArr[2] <= 5; 
               numArr[3] = temp;      // numArr[3] <= 9
            */   
               
               int temp = numArr[j];
               numArr[j] = numArr[j+1];
               numArr[j+1= temp; 
            }   
         }// end of for----------------------
         
      }// end of for---------------------------
      
      System.out.println("\n=== 오름차순 정렬한 후 ===");
      for(int i=0; i<numArr.length; i++) {
         String str = (i<numArr.length-1)?",":"\n";
         System.out.print(numArr[i]+str);
      }// end of for---------------------
      
      System.out.println("\n~~~~~~~~~~~~~~~~~~~\n");
      
      int[] numArr2 = {9,7,3,5,1}; 
      
      System.out.println("=== 정렬하기 전 ===");
      for(int i=0; i<numArr2.length; i++) {
         String str = (i<numArr2.length-1)?",":"\n";
         System.out.print(numArr2[i]+str);
      }// end of for---------------------
      
      // === 내림차순 정렬하기 === //
      for(int i=0; i<numArr2.length-1; i++) { 
         
         for(int j=0; j<numArr2.length-1-i; j++) { 
         
            if(numArr2[j] < numArr2[j+1]) {
               int temp = numArr2[j];
               numArr2[j] = numArr2[j+1];
               numArr2[j+1= temp; 
            }   
         }// end of for----------------------
         
      }// end of for---------------------------
      
      System.out.println("\n=== 내림차순 정렬한 후 ===");
      for(int i=0; i<numArr2.length; i++) {
         String str = (i<numArr2.length-1)?",":"\n";
         System.out.print(numArr2[i]+str);
      }// end of for---------------------
      
      
      System.out.println("\n~~~~~~~~~~~~~~~~~~~\n");
      
      int[] numArr3 = {9,7,3,5,1}; 
      
      System.out.println("=== 정렬하기 전 ===");
      for(int i=0; i<numArr2.length; i++) {
         String str = (i<numArr2.length-1)?",":"\n";
         System.out.print(numArr2[i]+str);
      }// end of for---------------------
      
      Arrays.sort(numArr3);  // 오름차순 정렬
      
      System.out.println("\n=== Arrays.sort()를 사용하여 정렬한 후 ===");
      for(int i=0; i<numArr3.length; i++) {
         String str = (i<numArr3.length-1)?",":"\n";
         System.out.print(numArr3[i]+str);
      }// end of for---------------------
 
   }// end of main()--------------------------------
 
}
 
cs

Comments

No comments yet. Be the first!

    164 posts in 테크

    15 / 164