我编写这个解决方案是为了提供一些关于 C 编程和任何其他语言的重要技巧。
- 代码必须是可读的,这可以通过
functions 来实现,并给它们起有意义的名字。
- 函数不应冗长复杂(逻辑分开)让每个函数执行 1 个任务。
- 始终检查参数(来自应用程序外部的参数,例如用户输入或任何其他
API 用户)。
- 检查和验证函数参数
affect performance!当不需要检查时,我们不检查。例如我们必须检查system callmalloc()的返回值,因为如果分配失败我们不想让整个程序崩溃!
- 当您谈论 >= 0 的尺寸时,请使用
size_t!
- 在函数声明中使用
const(可以保护地址和参数值),让编译器帮你强制执行语言规则和你自己的规则!
- 考虑性能(如果你需要,但 C 是为性能而生的 :-)),使用
derefernce operator 访问 arrays 类似指针,astrisc or star * 比运算符 subscribt [] 更快
- 祝你好运。 C 是有史以来最优雅、最强大的语言之一!
代码片段
enter code here
#include <stdio.h>
#include <stdlib.h>
/*swap two int varibles*/
void f_swap(int* lhs, int* rhs)
{
int temp = *rhs;
*rhs = *lhs;
*lhs = temp;
}
/*status enum*/
typedef enum E_STAT {
success_status = 0x0,
allocation_failed = 0x1,
invalid_user_inputs = 0x2,
/*... you can add if you want/need*/
failure_status
}E_STAT;
const char* f_status_to_str(E_STAT stat)
{
static const char* STATUS_MSG[4] = {
"success_status",
"allocation_failure",
"invalid_user_inputs",
"failure_status" };
return STATUS_MSG[stat];
}
void f_fill_array(int* p_ret_arr, size_t arr_size)
{
printf("Enter the elements of the array below:\n");
for (size_t i = 0; i < arr_size; ++i)
{
/*scanf("%d", &p_ret_arr[i]);*/ /*or we can take them in the form next line*/
printf("Enter the -%lu- element:", i);
scanf("%d", (p_ret_arr + i));
//puts("");
}
}
void f_sel_sort(int* const p_arr, size_t arr_size)
{
size_t i, j, min_idx;
/* One by one move boundary of unsorted subarray */
for (i = 0; i < arr_size - 1; i++)
{
/* Find the minimum element in unsorted array */
min_idx = i;
for (j = i + 1; j < arr_size; ++j)
{
if (p_arr[j] < p_arr[min_idx])
{
min_idx = j;
}
}
/*Swap the found minimum element with the first element */
f_swap(&p_arr[min_idx], &p_arr[i]);
}
}
void f_print_array(const int* const p_arr, size_t arr_size)
{
for (size_t j = 0; j < arr_size; ++j)
{
printf("%d ", *(p_arr + j));
}
}
/*allocate new int array on the heap (dyn allocation)*/
int* f_allocate(size_t arr_size)
{
int* p_ret = NULL;
return (p_ret=(int*)malloc(sizeof(int) * arr_size));
}
E_STAT f_get_arr(int** p_ret_arr, size_t* arr_size)
{
E_STAT stat;
printf("Please enter array size below:\n");
scanf("%lu", arr_size);
/*recomended to check the arr_size and do some limiting on this variable if you wish*/
*p_ret_arr = f_allocate(*arr_size);
if (!(*p_ret_arr))
{
stat = allocation_failed;
return stat;
}
f_fill_array(*p_ret_arr, *arr_size);
stat = success_status;
return stat;
}
int main(int argc, char* argv[])
{
size_t arr_size = 0;
int* arr = NULL;
E_STAT stat;
stat = f_get_arr(&arr, &arr_size);
if (stat != success_status)
{
printf("Error: %s\n", f_status_to_str(stat));
abort();
}
f_sel_sort(arr, arr_size);
printf("Sorted array elements:\n");
f_print_array(arr, arr_size);
return 0;
}