It's a tragedy. I 've written a lot of things. I want to change the attribute to the source code, but I don't have much to do with it.
How sorting works
public void SelectionSort(int[] arr)
{
int temp;
int min;
for (int outer = 0; outer <= arr.GetUpperBound(0); outer++)
{
min=outer;
for (int inner = outer + 1; inner <= arr.GetUpperBound(0); inner++)
{
if (arr[min] > arr[inner])
{
temp = arr[min];
arr[min] = arr[inner];
arr[inner] = temp;
}
}
}
}
Principle of Bubble Sorting:
(1) Compare arr [0], arr [1]. If arr [0]> arr [1],
(2) Compare arr [I-1], arr [I], if arr [I-1]> arr [I], swap until I = n-1, in this way, the maximum number is in the rightmost a [n-1 ].
(3) duplicate (1) (2) to n-I
public void BubbleSort(int[] arr)
{
int temp;
for (int outer = arr.GetUpperBound(0); outer >= 1; outer--)
{
for (int inner = 0; inner < outer; inner++)
{
if(arr[inner]>arr[inner+1])
{
temp = arr[inner];
arr[inner] = arr[inner + 1];
arr[inner + 1] = temp;
}
}
}
}
Principle of insertion sorting: Unlike Bubble sorting and selection sorting, insertion sorting mainly involves moving data. Anyone who has played the fight knows that there is a card on hand to insert the second card, sort by size. Once inserted, It is a sorted sequence. The difficulty is where to insert the data. Therefore, compare the data one by one and then insert the data to the proper position.
public void InsertionSort(int[] arr)
{
int temp;
int inner;
for (int outer = 1; outer <= arr.GetUpperBound(0); outer++)
{
inner = outer;
temp = arr[outer];
while (inner > 0 && temp < arr[inner - 1])
{
arr[inner] = arr[inner - 1];
inner--;
}
arr[inner] = temp;
}
}
Two simple search algorithms:
Sequential search: Applicable to unordered Series
public int LinearSearch(int[] arr, int elem)
{
for (int i = 0; i <= arr.GetUpperBound(0); i++)
{
if (arr[i] == elem)
return i;
}
return -1;
}
Binary Search: Applicable to sorted
(1) Recursion
public int BinarySearch(int[] arr, int elem,int low,int high)
{
int mid = (low + high) / 2;
if (low > high) return -1;
else
{
if (arr[mid] > elem)
return BinarySearch(arr, elem, low, mid - 1);
else if (arr[mid] < elem)
return BinarySearch(arr, elem, mid + 1, high);
else
return mid;
}
}
(2) iteration method
public int BinarySearch(int[] arr,int elem)
{
int low=0;
int high=arr.GetUpperBound(0);
int mid;
while (low <= high)
{
mid=(low+high)/2;
if (arr[mid] == elem)
return mid;
if (arr[mid] > elem)
high = mid - 1;
if (arr[mid] < elem)
low = mid + 1;
}
return -1;
}
Recursion and iteration: iteration (generally loop implementation) is more efficient, and Recursion (calling itself) is more hierarchical, making it easier for readers to understand, but the speed is not flattering.
Conclusion: Understand recursion and iteration, basic sorting and search algorithms, and prepare for future advanced algorithms.