-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombSort.java
More file actions
91 lines (76 loc) · 2.5 KB
/
CombSort.java
File metadata and controls
91 lines (76 loc) · 2.5 KB
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
import java.io.*;
import java.io.File;
import java.util.Scanner;
public class CombSort {
// To find gap between elements
int getNextGap(int gap)
{
// Shrink gap by Shrink factor
gap = (gap*10)/13;
if (gap < 1)
return 1;
return gap;
}
// Function to sort arr[] using Comb Sort
void sort(int arr[])
{
int n = arr.length;
// initialize gap
int gap = n;
// Initialize swapped as true to make sure that
// loop runs
boolean swapped = true;
// Keep running while gap is more than 1 and last
// iteration caused a swap
while (gap != 1 || swapped == true)
{
// Find next gap
gap = getNextGap(gap);
// Initialize swapped as false so that we can
// check if swap happened or not
swapped = false;
// Compare all elements with current gap
for (int i=0; i<n-gap; i++)
{
if (arr[i] > arr[i+gap])
{
// Swap arr[i] and arr[i+gap]
int temp = arr[i];
arr[i] = arr[i+gap];
arr[i+gap] = temp;
// Set swapped
swapped = true;
}
}
}
}
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String[] args) throws IOException{
File file = new File("D:\\KHAIRI\\2-Sem 3\\5- Data Structure\\Assignment 2\\combsort.txt");
Scanner sc = new Scanner(file);
long startTime = System.nanoTime();
String numString;
int num,count=0;
CombSort ob = new CombSort();
int arr[] = new int[99];
System.out.println("Data before sort: ");
while (sc.hasNextLine()) {
numString=sc.nextLine();
num=Integer.parseInt(numString);
arr[count]=num;
System.out.print(arr[count]+" ");
count++;
}
ob.sort(arr);
System.out.println("\nData after sort:");
printArray(arr);
long endTime = System.nanoTime();
System.out.println("Took "+(endTime - startTime) + " ns");
}
}