Skip to content

Commit 8098c8d

Browse files
authored
feat: add c# bubble and improve the algorithm (doocs#687)
1 parent 7436fdf commit 8098c8d

File tree

2 files changed

+96
-0
lines changed

2 files changed

+96
-0
lines changed
+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
using static System.Console;
2+
namespace Pro;
3+
public class Program
4+
{
5+
public static void Main()
6+
{
7+
int[] test = new int[] {56,876,34,23,45,501,2,3,4,6,5,7,8,9,11,10,12,23,34};
8+
BubbleSortNums(test);
9+
foreach (var item in test)
10+
{
11+
WriteLine(item);
12+
}
13+
ReadLine();
14+
}
15+
public static void BubbleSortNums(int[] nums)
16+
{
17+
int numchange = 0;
18+
for (int initial = 0; initial < nums.Length - numchange; initial++)
19+
{
20+
WriteLine($"{initial} start ");
21+
//记录此值 用于迭代开始位置
22+
bool changelog = false;
23+
for (int second_sortnum = initial; second_sortnum < nums.Length - 1; second_sortnum++)
24+
{
25+
if (nums[second_sortnum] > nums[second_sortnum + 1])
26+
{
27+
swap(ref nums[second_sortnum], ref nums[second_sortnum+ 1]);
28+
if (!changelog)
29+
{
30+
//记录转换的位置,让initial开始位置从转换位置前开始
31+
initial = ((second_sortnum - 2 )> 0) ? (second_sortnum - 2) : -1;
32+
numchange += 1;
33+
}
34+
changelog = true;
35+
}
36+
}
37+
}
38+
}
39+
private static void swap(ref int compare_left, ref int compare_right)
40+
{
41+
int temp = compare_left;
42+
compare_left = compare_right;
43+
compare_right = temp;
44+
}
45+
}

basic/sorting/BubbleSort/README.md

+51
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,57 @@ fn main() {
188188
}
189189
```
190190

191+
### **C#**
192+
```cs
193+
using static System.Console;
194+
namespace Pro;
195+
public class Program
196+
{
197+
public static void Main()
198+
{
199+
int[] test = new int[] {56,876,34,23,45,501,2,3,4,6,5,7,8,9,11,10,12,23,34};
200+
BubbleSortNums(test);
201+
foreach (var item in test)
202+
{
203+
WriteLine(item);
204+
}
205+
ReadLine();
206+
}
207+
public static void BubbleSortNums(int[] nums)
208+
{
209+
int numchange = 0;
210+
for (int initial = 0; initial < nums.Length - numchange; initial++)
211+
{
212+
WriteLine($"{initial} start ");
213+
//记录此值 用于迭代开始位置
214+
bool changelog = false;
215+
for (int second_sortnum = initial; second_sortnum < nums.Length - 1; second_sortnum++)
216+
{
217+
if (nums[second_sortnum] > nums[second_sortnum + 1])
218+
{
219+
swap(ref nums[second_sortnum], ref nums[second_sortnum+ 1]);
220+
if (!changelog)
221+
{
222+
//记录转换的位置,让initial开始位置从转换位置前开始
223+
initial = ((second_sortnum - 2 )> 0) ? (second_sortnum - 2) : -1;
224+
numchange += 1;
225+
}
226+
changelog = true;
227+
}
228+
}
229+
}
230+
}
231+
private static void swap(ref int compare_left, ref int compare_right)
232+
{
233+
int temp = compare_left;
234+
compare_left = compare_right;
235+
compare_right = temp;
236+
}
237+
}
238+
239+
240+
```
241+
191242
<!-- tabs:end -->
192243

193244
## 算法分析

0 commit comments

Comments
 (0)