bài giải bubble sort của cô Đoan
Diễn đàn cntt ĐH-TÔN ĐỨC THẮNG.Thân mời các anh em tham gia để diễn đàn phong phú hơn :: Tài liệu Môn học :: phân tích thiết kế thuật giải
Trang 1 trong tổng số 1 trang
bài giải bubble sort của cô Đoan
import java.io.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
public class thigiuaki {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
Scanner input = new Scanner(new FileInputStream("in.txt"));
PrintWriter output = new PrintWriter(new FileOutputStream("out.txt"));
String s = input.nextLine();
String[] val = null;
val = s.split(" ");
int[] a = new int[val.length];
for (int i=0;i<val.length;i++)
a[i] = Integer.parseInt(val[i]);
bubbleSort(a);
String result = "";
for (int j=0;j<a.length;j++)
result+=a[j]+" ";
result.trim();
System.out.print(result);
output.print(result);
output.flush();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void bubbleSort(int[] arr) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < arr.length - j; i++) {
if (arr[i] > arr[i + 1]) {
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
swapped = true;
}
}
}
}
}
//lưu ý phải tạo file in.txt trước, khi chạy sẽ tự động tạo ra file out.txt trong cùng folder chứ project đó
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
public class thigiuaki {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
Scanner input = new Scanner(new FileInputStream("in.txt"));
PrintWriter output = new PrintWriter(new FileOutputStream("out.txt"));
String s = input.nextLine();
String[] val = null;
val = s.split(" ");
int[] a = new int[val.length];
for (int i=0;i<val.length;i++)
a[i] = Integer.parseInt(val[i]);
bubbleSort(a);
String result = "";
for (int j=0;j<a.length;j++)
result+=a[j]+" ";
result.trim();
System.out.print(result);
output.print(result);
output.flush();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void bubbleSort(int[] arr) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < arr.length - j; i++) {
if (arr[i] > arr[i + 1]) {
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
swapped = true;
}
}
}
}
}
//lưu ý phải tạo file in.txt trước, khi chạy sẽ tự động tạo ra file out.txt trong cùng folder chứ project đó
Diễn đàn cntt ĐH-TÔN ĐỨC THẮNG.Thân mời các anh em tham gia để diễn đàn phong phú hơn :: Tài liệu Môn học :: phân tích thiết kế thuật giải
Trang 1 trong tổng số 1 trang
Permissions in this forum:
Bạn không có quyền trả lời bài viết
|
|